gpt4 book ai didi

javascript - 使用动画在 jQuery 中水平滑动框

转载 作者:行者123 更新时间:2023-11-30 12:46:00 25 4
gpt4 key购买 nike

我想在 jQuery 中使用动画左右滑动一个 div。到目前为止,我在 this fiddle 中包含以下内容.

问题是每次我向左或向右单击时,我的变量 left 都会返回到加载时的原始位置,而不是当前位置。我在这里做错了什么?我希望它在每次点击时向左移动,或在每次点击时从当前位置向右移动。

    <div id="yellowbox"></div>
<div id="left">left</div>
<div id="right">right</div>


<script>
var left = $('#yellowbox').offset().left;
console.log(left);

jQuery(document).on('click', '#left', function(event) {
$("#yellowbox").css({left:left}).animate({"left": (left -50)}, "slow");
});

jQuery(document).on('click', '#right', function(event) {
$("#yellowbox").css({left:left}).animate({"left": (left +50)}, "slow");
});
</script>

<style>
#yellowbox {
width: 50px;
height: 50px;
position: absolute;
top: 0;
right: 550px;
background: yellow;
}
</style>

最佳答案

您应该删除对 .css 的调用,没有它代码可以正常工作。因为,.css直接修改了位置,没有任何效果,然后就开始了动画。

DEMO

var left = $('#yellowbox').offset().left;


$(document).on('click', '#left', function(event) {
left -= 50; // you were not modifying the variable here
$("#yellowbox").animate({
"left": left
}, "slow");
});

$(document).on('click', '#right', function(event) {
left += 50; // you were not modifying the variable here
$("#yellowbox").animate({
"left": left
}, "slow");
});

关于javascript - 使用动画在 jQuery 中水平滑动框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22475536/

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