jQuery - moving embedded video to top?
The code below will find an image if it exists and move it above the title and text. So, if the markup looks like this:
<h2>Some fancy title</h2>
<p>Some interesting text</p>
<img src="someimage.jpg" />
or even this:
<p><h2>Some fancy title</h2></p>
<img src="someimage.jpg" />
<p>Some interesting text</p>
It will reposition elements so that it looks like this:
<img src="someimage.jpg" />
<h2>Some fancy title</h2>
<p>Some interesting text
Now, I'm trying to figure out how to rework the code so that if there's a video in the content (whether or not the post also has images), it will move the video above everything else. Can someone suggest or show me a way to do that?
This is the current code, as I have it right now:
$j('#hp-featured-item > div[id^="post-"]').each(function() {
if($j(this).find('embed')) {
var id=this.i开发者_如何学God.match(/^post-([0-9]+)$/);
var imgt = $j("img:eq(0)");
var pt = $j("p:not(:has(img)):eq(0)");
var hh = $j("h2:eq(0)");
$j(this).html('');
$j(this).append(imgt).append(hh).append(pt);
$j(this).each(function() {
var img = $j('img');
$j(img).wrap($j('<a>').attr('href', '/blog/?p='+id[1]));
var h2 = $j('h2');
$j(h2).wrap($j('<a>').attr('href', '/blog/?p='+id[1]));
});
} else {
var id=this.id.match(/^post-([0-9]+)$/);
var imgt = $j("embed:eq(0)");
var pt = $j("p:not(:has(embed)):eq(0)");
var hh = $j("h2:eq(0)");
$j(this).html('');
$j(this).append(imgt).append(hh).append(pt);
$j(this).each(function() {
var img = $j('embed');
$j(img).wrap($j('<a>').attr('href', '/blog/?p='+id[1]));
var h2 = $j('h2');
$j(h2).wrap($j('<a>').attr('href', '/blog/?p='+id[1]));
});
}
});
What you want to do is pretty straight forward with jQuery. I put together a test page and a suggested solution. Be sure to look at the source of the test page to see the original HTML content before it was rearranged.
You can view the test page here: http://pixelgraphics.s3.amazonaws.com/stackoverflow/1744585/index.html
Here is the rework of your jQuery code:
$j('#hp-featured-item > div[id^="post-"]').each(function() {
var $div = $j(this),
$h2 = $div.find('h2:first'),
$obj = $div.find('object, embed, img').filter(':first'),
id = this.id.match(/^post-([0-9]+)$/);
if( $obj.size() > 0){
// Find parent
var $par = $obj.closest('p');
// Move to top of div
$obj.prependTo($div);
// Remove the now empty parent
$par.remove();
if( $obj.is('img')){
// You can't wrap objects and embeds with links, so make sure we just wrap images
$obj.wrap( $j('<a></a>').attr('href', '/blog/?p='+id[1]));
}
}
// Wrap the contents of the h2, not the h2 itself, with a link
$h2.wrapInner( $j('<a></a>').attr('href', '/blog/?p='+id[1]) );
});
The only thing this doesn't do that your original code seemed to do was to remove all other content except the first img/embed, h2, and paragraph. This leaves the rest of the content in place. If you wanted to do that, then just add this line before the closing });
:
$div.children('p:gt(0)').remove();
精彩评论