[英]mouseenter works, mouseleave does not
我的mouseenter和mouseleave遇到問題。 我已經在堆棧和yt上查找了示例,但沒有發現任何有用的東西。 我假設我必須做兩個功能,或者也許只是重構為一個。 無論哪種方式,我們都會感激任何幫助。 我已經在html元素本身中聲明了50px的高度和寬度。 如果您需要我更具體的話。 我不是javascript專業人士,所以請不要生氣,以至於我沒有注意到任何事情。 如果我只是向我解釋,那么我知道以供將來參考。 謝謝!
var modWidth; $('#icons a img').on('mouseenter', function(){ $(this).width(modWidth); $(this).height(modWidth); var modWidth = 75; }); $('#icons a img').on('mouseleave', function(){ $(this).width(modWidth); $(this).height(modWidth); var modWidth = 50; });
您只需要聲明一次modWidth
,否則您需要在使用modWidth
之前為其設置一個數字,請參見小提琴https://jsfiddle.net/kvb5hb6f/1/
var modWidth;
$('#demo').on('mouseenter', function() {
modWidth = 75;
$(this).width(modWidth);
$(this).height(modWidth);
});
$('#demo').on('mouseleave', function() {
modWidth = 50;
$(this).width(modWidth);
$(this).height(modWidth);
});
問題是您通過在每個函數內部創建一個新的modWidth
來隱藏 modWidth
變量。 例如:
var myName = 'Mike'; function bob() { var myName = 'Bob'; console.log('My name is ' + myName); } bob(); // Notice that `bob` does not overwrite the original `myName` // It created a new `myName` in it's own scope console.log('My name is ' + myName);
為了避免這種情況,只需聲明一次modWidth
。
var modWidth; $('#icons a img').on('mouseenter', function() { $(this).width(modWidth); $(this).height(modWidth); modWidth = 50; // Notice that I removed `var` }); $('#icons a img').on('mouseleave', function() { $(this).width(modWidth); $(this).height(modWidth); modWidth = 75; // Notice that I removed `var` });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="icons"> <a href="#"> <img src="https://placehold.it/50x50"> </a> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.