我有一些代码旨在允许用户通过单击向侧面滚动,这在 jsfiddle 上完美运行,但在我的实际网站上做了一些完全不同的事情。在我的网站上,您可以向右滚动一次但不能再滚动,当您向后滚动时,它显然会向右滚动超过左侧边框。
这是我网站上问题的实时链接:rouvou.com/error
这是 fiddle .
我从字面上复制并粘贴了代码。我在我的网站上使用 jQuery 1.10.0,而 jsfiddle 最接近的 jQuery 版本是 1.10.1,但我无法想象这会导致这种不同的行为。我发布的 html 是整个页面上唯一的代码。在这两个位置,我都在 Ubuntu 上使用 Chrome 版本 42.0.2311.152(64 位)。
为什么代码在 jsfiddle 和我的网站上可能有不同的结果?
$(document).ready(function() {
var $item = $('div.item'), //Cache your DOM selector
visible = 2, //Set the number of items that will be visible
index = 0, //Starting index
endIndex = ($item.length / visible) - 1; //End index
$('div#arrowR').click(function() {
if(index < endIndex) {
index++;
$item.animate({
'left': '-=300px'
});
}
});
$('div#arrowL').click(function() {
if(index > 0) {
index--;
$item.animate({
'left': '+=300px'
});
}
});
});
#container {
width: 340px;
height: 50px;
}
#list-container {
overflow: hidden;
width: 300px;
float: left;
}
.list {
background: grey;
min-width: 1400px;
float: left;
}
#arrowR {
background: yellow;
width: 20px;
height: 50px;
float: right;
cursor: pointer;
}
#arrowL {
background: yellow;
width: 20px;
height: 50px;
float: left;
cursor: pointer;
}
.item {
background: green;
width: 140px;
height: 40px;
margin: 5px;
float: left;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="container">
<div id="arrowL">
</div>
<div id="arrowR">
</div>
<div id="list-container">
<div class='list'>
<div class='item'>1
</div>
<div class='item'>2
</div>
<div class='item'>3
</div>
<div class="item">4
</div>
<div class='item'>5
</div>
<div class='item'>6
</div>
<div class='item'>7
</div>
<div class="item">8
</div>
</div>
</div>
</div>
最佳答案
看来正如您所说,1.10.0
有一些错误。我创建了你的 jsfiddle 的修改版本,唯一的区别是 jQuery 使用的是版本 1.10.0
,您可以看到它现在像您的网站一样工作。
- Effects
#13937: finish() only finishes last item of a set being .animate()d.
#13939: 1.10.0 breaks relative animation
- Description
Relative animation (using += or -=) is broken in 1.10.0. For example, $('h1').animate({marginLeft: '+=100px'}); does not work.
因此,您可能必须切换到 1.10.x
版本,其中 x
是最新版本,因为它们的更改应该主要是问题修复,而不是功能更改。
关于javascript - 相同的代码在网站和 jsfiddle 上的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31883441/