2016-09-06 8 views
0

mouseenterとmouseleaveに問題があります。 Iveはstackとytの例を調べましたが、有用なものは何も見つかりませんでした。私は2つの機能を作ったり、リファクタを1つにする必要があると仮定しています。いずれにせよ、どんな助けにも感謝します。私はすでにhtml要素自体に高さと幅を50pxで宣言しています。あなたが私をもっともっと涼しくする必要があるなら。私は何かに気づかなかったので、私はjavascriptで専門家ではないので、動揺しないでください。私はちょうど私に説明したので、私は将来の参照のために知っている。ありがとう!mouseenterが動作し、mouseleaveが動作しない

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; 
 
});

+0

はあなただけ –

+0

第二のvar mouseleaveで宣言またはMouseEnterイベントは必要ない'たら、この変数を宣言する必要がありますすべての場合において「高さ」を有する。 [Function scope](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Function_scope)と[Hoisting](https://developer.mozilla.org/en-US)を参照してください。/docs/Glossary/Hoisting)。 – Li357

+0

実際にあなたが.width'と ''へundefined' '渡しているmodWidth' – Teemu

答えて

0

あなただけフィドル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); 
    }); 
0

問題があるあなたが見る、それを使用する前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>

関連する問題