javascript - Jquery - 如何为多个元素制作绑定点击事件?
问题描述
我正在使用 jquery 对图像进行动画处理,以制作混合图像,在单击时滚动不同部分。
我想过这样做
$("#head").click(function () {
if (headclix < 9) {
$("#head").animate({
left: "-=367px"
}, 500);
headclix++;
} else {
$("#head").animate({
left: "0px"
}, 500);
headclix = 0;
}
});
$("#eyes").click(function () {
if (eyeclix < 9) {
$("#eyes").animate({
left: "-=367px"
}, 500);
eyeclix++;
} else {
$("#eyes").animate({
left: "0px"
}, 500);
eyeclix = 0;
}
});
$("#nose").click(function () {
if (noseclix < 9) {
$("#nose").animate({
left: "-=367px"
}, 500);
noseclix++;
} else {
$("#nose").animate({
left: "0px"
}, 500);
noseclix = 0;
}
});
$("#mouth").click(function () {
if (mouthclix < 9) {
$("#mouth").animate({
left: "-=367px"
}, 500);
mouthclix++;
} else {
$("#mouth").animate({
left: "0px"
}, 500);
mouthclix = 0;
}
});
我希望有更好的方法来做到这一点
我想我可以在课堂上做点什么,但不知道如何让它发挥作用。需要使其成为点击事件并跟踪每个图像部分
$(".face").each(function (i) {
if (i < 9) {
$(".face").parent().animate({
left: "-=367px"
}, 500);
i++;
} else {
$(".face").parent().animate({
left: "0px"
}, 500);
i = 0;
}
});
HTML:
<div id="pic_box">
<div id="head" class="face"><img src="images/headsstrip.jpg"></div>
<div id="eyes" class="face"><img src="images/eyesstrip.jpg"></div>
<div id="nose" class="face"><img src="images/nosesstrip.jpg"></div>
<div id="mouth" class="face"><img src="images/mouthsstrip.jpg"></div>
</div>
谢谢你。
解决方案
您可以创建一个面部对象来保存每个面部部分的点击计数,以及一个处理点击事件的函数(下面命名为 clickHandler)。clickHandler 接受并在具有id
该元素的元素上调用适当的动画函数id
。
检查以下:
var face = {
"headClicks" : 0,
"eyesClicks" : 0,
"noseClicks" : 0,
"mouthClicks" : 0,
"clickHandler" : function(id) {
if(this[id+"Clicks"] < 9) {
animateLeft367(id);
this[id+"Clicks"]++;
} else {
animateLeft0(id);
this[id+"Clicks"] = 0;
}
}
}
function animateLeft367(id) {
$("#" + id).animate({left: "-=367px"}, 500);
console.log('animated ' + id + ' 367');
}
function animateLeft0(id) {
$("#" + id).animate({left: "0px"}, 500);
console.log('animated ' + id + ' 0');
}
$(".face").click(function() {
face.clickHandler(this.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="pic_box">
<div id="head" class="face"><img src="images/headsstrip.jpg"></div>
<div id="eyes" class="face"><img src="images/eyesstrip.jpg"></div>
<div id="nose" class="face"><img src="images/nosesstrip.jpg"></div>
<div id="mouth" class="face"><img src="images/mouthsstrip.jpg"></div>
</div>
推荐阅读
- c# - .net 核心发送 ClaimsPrincipal 作为操作的响应
- arrays - 在相等检查后更改索引值 wrt 数组的最大值
- spring - 带有 Spring 的嵌入式 Tomcat 抛出 IllegalAccessError:
无法访问其超接口 - python - 从文本文件创建嵌套字典
- reactjs - 使用 AntDesign 和 PrimeReact React 可避免的重新渲染问题
- c# - 如何在字典键中添加占位符花括号
- html - 撇号在 windows、chrome 浏览器中显示为 ’
- c - C 编程使用 malloc 和赋值
- razor - 无法在 ASP.NET 核心 2.0 类项目中使用 TagHelper 在“cshtml”中添加条码
- dependencies - python的所有RDEPENDS是否需要在Yocto的IMAGE_INSTALL_append中显式定义?