我创建了一个简单的代码,用于使用JQuery和CSS滑动切换图像。当您点击另一个图像时,我使用了多种功能来隐藏/切换其他功能。有没有一种方法来最大限度地减少这种使用?另外,当我第三次点击不同的图像时,我必须在它向后滑动之前双击。我的代码..及其JSFiddle简化每个ID的多个功能
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("#img1").toggle(
function() {
$("#img1").css({"transform": "translate3d(-100px, 0px, 0px)"});
$("#img2").css({"transform": "translate3d(0px, 0px, 0px)"});
$("#img3").css({"transform": "translate3d(0px, 0px, 0px)"});
},
function() {
$("#img1").css({"transform": "translate3d(0px, 0px, 0px)"});
}
);
$("#img2").toggle(
function() {
$("#img2").css({"transform": "translate3d(-100px, 0px, 0px)"});
$("#img1").css({"transform": "translate3d(0px, 0px, 0px)"});
$("#img3").css({"transform": "translate3d(0px, 0px, 0px)"});
},
function() {
$("#img2").css({"transform": "translate3d(0px, 0px, 0px)"});
}
);
$("#img3").toggle(
function() {
$("#img3").css({"transform": "translate3d(-100px, 0px, 0px)"});
$("#img2").css({"transform": "translate3d(0px, 0px, 0px)"});
$("#img1").css({"transform": "translate3d(0px, 0px, 0px)"});
},
function() {
$("#img3").css({"transform": "translate3d(0px, 0px, 0px)"});
}
);
});
</script>
</head>
<title></title>
<style>
.cardcont img {
transition: transform .2s ease-in-out;
}
.cardcont #img1 {
position:absolute;
left:0;
top:0;
z-index:-1;
}
.cardcont #img2 {
position:absolute;
left:200px;
top:0;
z-index:-1;
}
.cardcont #img3 {
position:absolute;
left:400px;
top:0;
z-index:-1;
}
</style>
</head>
<body>
<div class="cardcont">
<img src="http://i65.tinypic.com/fokk9j.jpg" id="img1"/>
<img src="http://i65.tinypic.com/fokk9j.jpg" id="img2"/>
<img src="http://i65.tinypic.com/fokk9j.jpg" id="img3"/>
</div>
</body>
</html>
您是否尝试过使用'class'名称而不是'ID'? – NewToJS
示例https://jsfiddle.net/166sb7ys/4/使用类名称将允许您使用一个函数来运行它 – NewToJS