gpt4 book ai didi

javascript - 如何仅使用 'on mouseenter' 和 'on mouseleave' 一次变量?

转载 作者:行者123 更新时间:2023-12-03 11:11:27 26 4
gpt4 key购买 nike

我有多个不同大小的对象,我希望每个对象在 mouseenter 上显示附加框并在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com