使用不同事件的相同功能 [英] using the same function of different events
问题描述
这看起来很简单,但我无法弄清楚。我是javascript / jquery的新手。
This seems pretty simple, but I can't figure it out. I'm new to javascript/ jquery.
我想触发一个函数移动div onmouseover,另一个onmouseout。我想在几个不同的div上调用这个相同的函数。如果不编写多个函数,我该怎么做?
i want to trigger a function to move a div onmouseover, and another onmouseout. I want to call this same function on several different divs. how would I do this without writing multiple functions?
<div id="indexJoinBanner" onmouseover="moveDivRight()" onmouseout="moveDivLeft()">
<!-- end #indexJoinBanner --></div>
<div id="indexJoinBanner2" onmouseover="moveDivRight()" onmouseout="moveDivLeft()">
<!-- end #indexJoinBanner2 --></div>
function moveDivRight(){
$("#indexJoinBanner").animate({
left: "0px",
},500 );
};
function moveDivLeft() {
$("#indexJoinBanner").animate({
left: "-150px",
},500 );
}
谢谢
推荐答案
您可以将div传递给函数,如
You can pass the div to the function like
<div id="indexJoinBanner" onmouseover="moveDivRight(this)" onmouseout="moveDivLeft(this)">
并在函数中使用
function moveDivRight(div){
$(div).animate({
left: "0px",
},500 );
};
function moveDivLeft(div) {
$(div).animate({
left: "-150px",
},500 );
}
此
在属性指定当前元素。
this
in the attributes specify the current element.
或者,您可以使用 .on()
而不是onmouseover和onmouseout属性附加处理程序,给你想要附加一个类的处理程序的所有元素然后
Alternatively you can attach handler using .on()
instead of onmouseover and onmouseout attributes, give all the elements you want to attach the handler a class then
$('.someclass').on('mouseover', function () {
$(this).animate({
left: "0px",
},500 );
}).on('mouseout', function () {
$(this).animate({
left: "-150px",
},500 );
})
这篇关于使用不同事件的相同功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!