【问题标题】:JQuery on with multiple events for mutiple elementsJQuery on 多个元素的多个事件
【发布时间】:2017-03-23 01:51:01
【问题描述】:

毫无疑问它可以工作,但我知道这不是一个好的代码。所以我想完成

  • 使用on() 使其工作

    <script>
        $(document).on("mouseenter", ".BUTTON_ONE", function() {
            $(this).animate({ 
                \'padding-right\' : 10,
            },30);
        });
        $(document).on("mouseleave", ".BUTTON_ONE", function() {
            $(this).animate({ 
                \'padding-right\' : 4,
            },30);
        });
        $(document).on("mouseenter", ".BUTTON_TWO", function() {
            $(this).animate({ 
                \'padding-left\' : 10,
            },30);
        });
        $(document).on("mouseleave", ".BUTTON_TWO", function() {
            $(this).animate({ 
                \'padding-left\' : 4,
            },30);
        });
        $(document).on("mouseenter", ".BUTTON_THREE", function() {
            $(this).animate({ 
                \'padding-left\' : 10,
            },30);
        });
        $(document).on("mouseleave", ".BUTTON_THREE", function() {
            $(this).animate({ 
                \'padding-left\' : 4,
            },30);
        });
     </script>
    

【问题讨论】:

    标签: jquery jquery-on


    【解决方案1】:

    也许是这样的::)

    $(document).ready(function() {
        $(document.body)
        .on({
            'mouseenter': function(e) { animate_padding_right(e,10); },
            'mouseleave': function(e) { animate_padding_right(e,4); }
        }, ".BUTTON_ONE")
        .on({
            'mouseenter': function(e) { animate_padding_left(e,10); },
            'mouseleave': function(e) { animate_padding_left(e,4); }
        }, ".BUTTON_TWO,.BUTTON_THREE");
    });
    function animate_padding_left(e,val) {
        $(e.target).animate({'padding-left':val},30);
    }
    function animate_padding_right(e,val) {
        $(e.target).animate({'padding-right':val},30);
    }
    

    请注意,我使用$(document.body),因为它在这种情况下更快且更有效。

    工作小提琴:http://www.codeply.com/go/uUoOo1vlaB

    【讨论】:

    • 感谢您的回答,但没有成功,控制台中的missing : after property id
    • 啊,抱歉我没有事先测试我的代码>w
    • 用单引号包裹mouseentermouseleave,所以变成'mouseenter''mouseleave' :D 希望它现在可以工作
    • 我已经更正了我的脚本并且它已经过测试并且运行顺利。 :) 希望对您有所帮助。
    猜你喜欢
    • 2013-03-13
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多