简体   繁体   English

鼠标事件的Javascript函数

[英]Javascript Function for mouse events

I am trying to change the following code so that instead of having to click-and-hold the linked image to make it bigger (150 into 300), I could click it once to make the image bigger, and click it again to make the image return to smaller. 我正在尝试更改以下代码,以便不必单击并按住链接的图像将其放大(从150变为300),可以单击一次以使图像变大,然后再次单击以使它变大。图像缩小。 I have to do this with multiple images on the page. 我必须使用页面上的多个图像来执行此操作。 (Be forewarned, I do not really understand jquery and have a very basic understanding of javascript. But I'm learning!) (请预先警告,我不太了解jquery,对javascript有非常基本的了解。但是我正在学习!)

function Down(sender)
{ var thisWidth=parseInt(sender.style.width.replace('px',''));
    sender.style.width=(300) + 'px';}
function Up(sender)
{ var thisWidth=parseInt(sender.style.width.replace('px',''));
    sender.style.width=(150) + 'px';}'

<img src="picture.jpg" onmousedown="Down(this)" onmouseup="Up(this)" />

You could toggle a class. 您可以切换课程。

Firstly, you should set a class to target specific element(s) and setting width attribute is preferred method: 首先,您应该将一个类设置为针对特定元素,并且设置width属性为首选方法:

<img class="imgToggling" src="picture.jpg" width="150">

Now, set relevant CSS for a big class: 现在,一组相关的CSS big类:

.big {
    width: 300px;
}

Then on click, toggle this class, binding event using jQuery (preferred over inline scripting): 然后单击,切换此类,使用jQuery绑定事件(优先于内联脚本):

$(function () { //shorthand for document ready handler
    $('.imgToggling').on('click', function () {
        $(this).toggleClass('big');
    });
});

-DEMO- -演示-

If you wish to get some kind of transition, add this CSS rule eg: 如果您希望获得某种过渡,请添加此CSS规则,例如:

img.imgToggling {
    -webkit-transition: width 1s ease-in-out;
    -moz-transition: width 1s ease-in-out;
    -o-transition: width 1s ease-in-out;
    transition: width 1s ease-in-out;
}

-DEMO with transition- -演示与过渡-

I have to do this with multiple images on the page. 我必须使用页面上的多个图像来执行此操作。

Then you can do this with jQuery (as jQuery is tagged) : 然后,您可以使用jQuery (因为标记了jQuery)执行此操作:

$('img').on('click', function(){
     var thisWidth=$(this).width(),
         setWidth = thisWidth >= 300 ? 150 : 300;
     $(this).width(setWidth); 
});

assumed if images are not dynamically generated or placed with ajax in the dom. 假定图像不是动态生成的,也不是在dom中用ajax放置的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM