我在同一个页面上有两个不同的div,它们需要以完全相同的方式滚动内容。我目前的代码运行得很好,但是可能有一种更理想的方法来实现这一点。我只是不知道如何告诉jQuery在同一个函数中对#container-1使用#move-1,对#container-2使用#move-2。有人能告诉我怎么做吗?
HTML
<div id="container-1" class="container">
<div class="item item-1">container 1 - item 1</div>
<div class="item item-2">container 1 - item 2</div>
<div class="item item-3">container 1 - item 3</div>
</div>
<button id="move-1">Move item in container 1</button>
<div id="container-2" class="container">
<div class="item item-1">container 2 - item 1</div>
<div class="item item-2">container 2 - item 2</div>
<div class="item item-3">container 2 - item 3</div>
</div>
<button id="move-2">Move item in container 2</button>jQuery
$( "#move-1" ).click(function()
{
$( "#container-1 .item" ).animate({ "top": "-=200px" }, "slow" );
});
$( "#move-2" ).click(function()
{
$( "#container-2 .item" ).animate({ "top": "-=200px" }, "slow" );
});CSS
body {
background: #fff;
}
.container {
position: relative;
background-color: #f5f5f5;
width: 240px;
height: 200px;
overflow: hidden;
font-family: arial, sans;
font-weight: bold;
text-align: center;
}
.item {
position: absolute;
width: 190px;
height: 90px;
color: #000;
overflow: auto;
}
.item-1 {
top: 0px;
}
.item-2 {
top: 200px;
}
.item-3 {
top: 400px;
}
button {
margin-bottom: 20px;
}JSFIDDLE
发布于 2015-01-16 23:20:54
您可以使用所单击元素的ID并获取编号
$('[id^="move-"]').on('click', function() {
var id = this.id.split('-').pop();
$('#container-' + id + ' .item').animate({ "top": "-=200px" }, "slow" );
});发布于 2015-01-16 23:30:47
非常简单,如果你的超文本标记语言是相同的,你可以使用prev()来获取前面的元素,然后在里面找到子元素:
$('button').click(function() {
$(this).prev().find('.item').animate({ "top": "-=200px" }, "slow" );
});FIDDLE
https://stackoverflow.com/questions/27987111
复制相似问题