jQuery 应用 css 偏移(裁剪)显示的图像
jQuery to apply css to offset (crop) displayed image
我想应用 css 来偏移在元素的自定义数据属性中设置的百分比显示的图像。
HTML:
<div class="cover">
<img src="/path_to_some_image.jpg" data-offset_y="15">
<img src="/path_to_some_image.jpg" data-offset_y="18">
<img src="/path_to_some_image.jpg" data-offset_y="24">
<img src="/path_to_some_image.jpg" data-offset_y="7">
</div>
jQuery:
$(document).ready(function() {
$(.cover img).load(function (offset_y) {
var cover_w = 850;
var cover_h = 315;
var img_w = $(this).width ();
var img_h = $(this).height ();
var real_img_h = (cover_w * img_h / img_w) - cover_h;
$(this).css ({ top: parseInt (real_img_h * offset_y / 100 * -1) + "px" });
});
})
我需要一些指导。
编辑:
$(document).ready(function() {
$(".brand-cover img").load(function(offset_y) {
var cover_w = 350;
var cover_h = 130;
var img_w = $(this).width ();
var img_h = $(this).height ();
var real_img_h = (cover_w * img_h / img_w) - cover_h;
$(this).css ({ top: (real_img_h * $(this).data("offset_y") / 100 * -1) });
});
})
不确定这是否是您想要的,但这里是代码
$(document).ready(function () {
$(".cover").find("img").each(function () {
var cover_w = 850;
var cover_h = 315;
var img_w = $(this).width();
var img_h = $(this).height();
var real_img_h = (cover_w * img_h / img_w) - cover_h;
$(this).css({
// top: parseInt(real_img_h * $(this).data("offset_y") / 100 * -1) + "px"
// this equally does the job
top: real_img_h * $(this).data("offset_y") / 100 * -1
});
});
});
然后确保父容器.cover
和图像有CSS相对位置
.cover, .cover img {position: relative}
* jsfiddle 已更新
我想应用 css 来偏移在元素的自定义数据属性中设置的百分比显示的图像。
HTML:
<div class="cover">
<img src="/path_to_some_image.jpg" data-offset_y="15">
<img src="/path_to_some_image.jpg" data-offset_y="18">
<img src="/path_to_some_image.jpg" data-offset_y="24">
<img src="/path_to_some_image.jpg" data-offset_y="7">
</div>
jQuery:
$(document).ready(function() {
$(.cover img).load(function (offset_y) {
var cover_w = 850;
var cover_h = 315;
var img_w = $(this).width ();
var img_h = $(this).height ();
var real_img_h = (cover_w * img_h / img_w) - cover_h;
$(this).css ({ top: parseInt (real_img_h * offset_y / 100 * -1) + "px" });
});
})
我需要一些指导。
编辑:
$(document).ready(function() {
$(".brand-cover img").load(function(offset_y) {
var cover_w = 350;
var cover_h = 130;
var img_w = $(this).width ();
var img_h = $(this).height ();
var real_img_h = (cover_w * img_h / img_w) - cover_h;
$(this).css ({ top: (real_img_h * $(this).data("offset_y") / 100 * -1) });
});
})
不确定这是否是您想要的,但这里是代码
$(document).ready(function () {
$(".cover").find("img").each(function () {
var cover_w = 850;
var cover_h = 315;
var img_w = $(this).width();
var img_h = $(this).height();
var real_img_h = (cover_w * img_h / img_w) - cover_h;
$(this).css({
// top: parseInt(real_img_h * $(this).data("offset_y") / 100 * -1) + "px"
// this equally does the job
top: real_img_h * $(this).data("offset_y") / 100 * -1
});
});
});
然后确保父容器.cover
和图像有CSS相对位置
.cover, .cover img {position: relative}
* jsfiddle 已更新