我有多个不同大小的对象,我希望每个对象显示其他框on mouseenter并隐藏on mouseleave。我有一个完美做到这一点的jquery脚本,我唯一关心的是我重复了两次变量,并且有些事情告诉我,无需重复自己就可以做到这一点。

问题是它们都强烈地基于$(this)核心元素,因此我不能将变量设为全局。我的猜测是我应该在调用on mouseenteron mouseleave之前将它们与元素容器函数放在一起,但是从语法的角度来看,我不知道该怎么做。但是同样,我可能会犯错。

这是代码:

$(document).ready(function() {

    $('.box-options').hide();

    var $boxModule = $('div.box');

    $boxModule.on({

        mouseenter: function() {

            var $this = $(this),                               // repeat
                $options = $this.find('div.options'),          // repeat
                $optionsBox = $this.find('div.options-box');   // repeat

            var boxHeight = $this.height(),                    // repeat
                boxWidth = $this.width(),                      // repeat
                optionsBoxHeight = $optionsBox.outerHeight();  // repeat

            if ( // statement referring to variables above }
            else {  // statement referring to variables above };

            $options.fadeIn(200).addClass('shadow').css({"height" : boxHeight + optionsBoxHeight});
            $optionsBox.delay(100).fadeIn(200).css({"top" : boxHeight}, 200);
        },

        mouseleave: function() {

            var $this = $(this),                                 // repeat
                $options = $this.find('div.options'),          // repeat
                $optionsBox = $this.find('div.options-box');   // repeat

            var boxHeight = $this.height(),                    // repeat
                boxWidth = $this.width(),                      // repeat
                optionsBoxHeight = $optionsBox.outerHeight();  // repeat

            $optionsBox.hide().css({"top" : boxHeight});
            $options.hide().removeClass('shadow').css({"height" : boxHeight}, 200);
        }
    });
});


显然,代码包含更多行,但是重要的部分是标记为// repeat的变量。有谁知道我如何重新构造代码以使变量仅写入一次?

更新:我更新了代码以更好地描述逻辑。为了清楚起见,在每个页面上还有多个对象,它们具有相同的类,结构和大小,唯一的不同是内容(文本)和id编号。

最佳答案

使用hover函数,对于变量,在悬停事件之前声明它们,就像对$boxModule所做的那样。

呼唤

$( selector ).hover( handlerIn, handlerOut )


是以下内容的简写:

$( selector ).mouseenter( handlerIn ).mouseleave( handlerOut );

关于javascript - 如何在“on mouseenter”和“on mouseleave”上仅使用一次变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27564513/

10-09 18:14
查看更多