我正在尝试制作一个图像 slider ,我基本上将图像水平排列(每个图像宽度为 700 像素,高度不同),然后使用 JQuery 为向右或向左滑动 700 像素设置动画以显示下一张图像。我是 jQuery 的新手,我不确定我的下一步是什么以及我的 CSS 应该喜欢什么才能完成这项工作。
jQuery
$("#slideRight").click(function() {
$("#slider").animate({right:700});
});
$("#slideLeft").click(function() {
$("#slider").animate({left:700});
});
HTML
<div id="slideButtons">
<input type="button" value="next L" id="slideLeft" />
<input type="button" value="next R" id="slideRight" />
</div>
<div id="slider">
<img src="slideTest.jpg" alt="" />
<img src="slideTest2.jpg" alt="" />
<img src="slideTest3.jpg" alt="" />
</div>
CSS
#slider {
height: auto;
width: 700px;
position: relative;
background-color: blue;
}
最佳答案
如果您真的对构建图像 slider 感兴趣,这里是我很快可以构建的方式。
注意:- 我已经使用隐藏和显示方法来实现 slider ,您可以使用多种方法来实现。请遵循逻辑而不是直接使用代码。
逻辑很简单
- 生成 id 值设置为连续整数的图像
- 通过设置属性 display none 使所有图像隐藏
- 使第一个元素可见
- 然后当单击下一个按钮时,检查您是否在最后一张图片,如果是,则显示第一张图片,如果不是,则显示下一张图片
- 要找到下一张图片,您可以获取当前可见图片 ID 并将其加 1 以获得下一张连续图片
- 与上一张类似,您可以减去显示上一张图像
- 在显示上一张图像时,如果显示最后一张图像,则必须检查您是否正在查看第一张图像。否则通过按照步骤 6 计算 id 显示上一张图像
这是我尝试为这个问题构建的示例粗略代码,(未测试)
// First make the first image visible
$(".slide-content img:first-child").show();
// Bind the click handler
$("#slideRight").click(function() {
// if there is only one image in the slider then return false
if($(".slide-content > img").length == 1)
{
return false;
}
// Set current to the visible element
var current = $(".slide-content > img:visible").attr('id');
// hide the visible element
$('#'+current).hide();
if(current == $(".slide-content > img").length )
{
current = 1;
}
else
{
current = parseInt(current)+1;
}
$('#'+current).show();
});
$("#slideLeft").click(function() {
if($(".slide-content > img").length == 1)
{
return false;
}
var current = $(".slide-content > img:visible").attr('id');
$('#'+current).hide();
if(current == 1)
{
current = $(".slide-content > img").length;
}
else
{
current = parseInt(current)-1;
}
$('#'+current).show();
});
<div id="slideButtons">
<input type="button" value="next L" id="slideLeft" />
<input type="button" value="next R" id="slideRight" />
</div>
<div class="slide-content">
<img id = '1' src="slideTest.jpg" alt="" />
<img id = '2' src="slideTest2.jpg" alt="" />
<img id = '3' src="slideTest3.jpg" alt="" />
</div>
关于jquery - 使用隐藏图像的基本图像 slider ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12356095/