【发布时间】:2011-01-22 13:22:09
【问题描述】:
我正在尝试使用 JQuery 使用文章中存在的图像创建动态页眉。我打算给图像一个类(.thumbnail)。一旦用于标题,我想从文章中删除图像。逻辑如下:
- 使用 .thumbnail 类查找 IMG 标签
- 将该图像移至新的 DIV (#dynHeader),将其归类为 .Image1
- 将图像高度缩放为 x 像素,宽度保持纵横比
- 查找新缩放图像的宽度(var保持宽度)
- 计算#dynHeader的剩余宽度
- 将IMG复制到.Image1右侧,命名为.Image2
- 将其宽度设置为保持宽度的值
- 将其裁剪到 .Image1 的高度
- 以特定值将其定位在 Y 轴上
我需要知道如何查找和复制 IMG .thumbnail。我确信随着我继续解决这个问题,会出现更多问题,但我完全被困住了。我想错了吗?有没有办法在页面上放置两次相同的图像?
感谢您的帮助。
-亚历克斯
编辑:我正在发布解决方案,因为我正在我的网站上为可能遇到此问题的任何其他人使用它。从答案中提取代码并对其进行调整以使其正常运行。
//need to clone before removing class so that the original is deletable later.
var cache = $('img.thumbnail').clone().removeClass('thumbnail').addClass('Image1').css('float','left');
//remove the original from the text
$('img.thumbnail').remove();
//attach the cloned image to the header
$('#dynHeader').append(cache);
//find the ratio
var ratio = (cache.width() / cache.height());
//set variable to hold image height
var imageHeight = (365);
//set variable to hold image width
var imageWidth = (imageHeight*ratio);
//set the image height & width
cache.height(imageHeight).width(imageWidth);
//figure the amount of width remaining in the header
var remainWidth = $('#dynHeader').width() - imageWidth;
//clone the header image
var dupe = cache.clone();
//work with the cloned image - change the class to Image2, set the width and height dupe.removeClass('Image1').addClass('Image2').css("width",remainWidth+"px").css("height","auto");
//place Image2 to the right of Image1
cache.after(dupe);
然后我使用一些 CSS 来定位 Image2 并隐藏溢出(我正在拍摄的缩放和裁剪效果)。
#dynHeader{
height: 365px;
overflow: hidden;
margin-bottom: 30px;
}
img.Image2{
position: relative;
top: -150px;
}
希望这对其他人有帮助!感谢 Alex 指出正确的方法。
【问题讨论】:
标签: javascript jquery image