gpt4 book ai didi

javascript - 在 div 内滚动大图像

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:47:35 24 4
gpt4 key购买 nike

我在一个小 div 中有一个大图像。在那个 div 里面有 4 个箭头来控制移动,右、下、左和上。箭头用于在较小的 div 内移动图像。

这是JS代码

$('.slide-right').click(function() {
$('.inner img').animate({ "right": "+=50px" }, "slow" );
});
$('.slide-bottom').click(function() {
$('.inner img').animate({ "bottom": "+=50px" }, "slow" );
});
$('.slide-left').click(function() {
$('.inner img').animate({ "left": "+=50px" }, "slow" );
});
$('.slide-top').click(function() {
$('.inner img').animate({ "top": "+=50px" }, "slow" );
});

这是 html:

<div id="content">
<div class="image-box">
<div class="inner"><img alt="" src="http://s15.postimg.org/5phzr2off/img.jpg" id="image" /></div>
<div id="arrow-up"><a href="javascript:void(0);" class="slide-top"><img alt="" src="http://s24.postimg.org/gr2uv14d1/arrow_top.png" /></a></div>
<div id="arrow-right"><a href="javascript:void(0);" class="slide-right"><img alt="" src="http://s24.postimg.org/ruda95avp/arrow_right.png" /></a></div>
<div id="arrow-bottom"><a href="javascript:void(0);" class="slide-bottom"><img alt="" src="http://s10.postimg.org/n8hv0166x/arrow_bottom.png" /></a></div>
<div id="arrow-left"><a href="javascript:void(0);" class="slide-left"><img alt="" src="http://s2.postimg.org/qrpm662u1/arrow_left.png" /></a></div>
</div>
</div>

演示:http://jsfiddle.net/john_bale96/C26rV/

我想让动画在到达图像边缘时停止。有人可以给我一些关于如何执行此操作的线索吗?

最佳答案

你必须考虑到,一开始,你的图像是left:0pxtop:0px。所以你已经有了你的左边和上面的限制。

$('.slide-left').click(function () {
if ($('.inner img').position().left + 50 < 0) {
$('.inner img').animate({
"left": "+=50px"
}, "slow");
}
});

$('.slide-top').click(function () {
if ($('.inner img').position().top + 50 < 0) {
$('.inner img').animate({
"top": "+=50px"
}, "slow");
}
});

然后,你可以得到右边和底部的限制。这是您的图像尺寸。

var limiteRight = 0 - $('.inner img').width() + $('.image-box').width();
var limiteBottom = 0 - $('.inner img').height() + $('.image-box').height();


$('.slide-right').click(function () {
if ($('.inner img').position().left - 50 > limiteRight) {
$('.inner img').animate({
"left": "-=50px"
}, "slow");
}
});

$('.slide-bottom').click(function () {
if ($('.inner img').position().top - 50 > limiteBottom) {
$('.inner img').animate({
"top": "-=50px"
}, "slow");
}
});

最后您必须检查您想要的新位置是否在此容器内。如果没有,就去limite。

$('.slide-right').click(function () {
if ($('.inner img').position().left - 50 > limiteRight) {
$('.inner img').animate({
"left": "-=50px"
}, "slow");
} else {
$('.inner img').animate({
"left": limiteRight
}, "slow");
}
});

FIDDLE 有完整的例子。

关于javascript - 在 div 内滚动大图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19449618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com