2017-12-01 10 views
0

これでかなり新しくなっていますが、マウスカーソルが<button>にあるときにページの背景色を変更したいのですが、カーソルがボタン上をホバーしているときに背景色を変更します。

jQuery.fn.mouseIsOver = function() { 
 
    if($(this[0]).is(":hover")) 
 
    { 
 
    return true; 
 
    } 
 
    return false; 
 
}; \t \t 
 
    
 
if($("b1").mouseIsOver()===true) 
 
{ 
 
    document.body.style.backgroundColor = "#AA0000"; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="b1", type="button">1</button>

[OK]を、ので、私はそのjQuery.fn ...どこからをコピーしたが、私はif(cond)が、私はマウスがボタンの上にホバリングしているかどうかを確認したいことを確認する方法がわからない、と場合は、背景色を変更します。

+0

理由は、文は1回だけ実行された場合ということです。ボタンが上がっているかどうかを継続的に確認するには、イベントリスナーを使用する必要があります。 – Yavor

答えて

0

コードでネイティブJSを主に使用している場合は、jQueryが必要ありません。必要なのはmouseoverイベントリスナーだけです。

document.getElementById('b1').addEventListener('mouseover',() => { 
 
    document.body.style.backgroundColor = '#aa0000'; 
 
});
<button id="b1", type="button">1</button>

0

あなたがIDをターゲットにする場合、あなたは自分のボタンにmouseentermouseleaveイベントリスナーを追加します。#(dieze)

$('#b1') 
+0

これは問題を解決しません – Luke

0
$("#b1").mouseover(function() { 
    $("div.background").css("color", "red"); 
}); 
0

でセレクタを開始する必要があります。この解決策のオーバーヘッドはjQueryの必要はありません。

document.getElementById('button').addEventListener('mouseenter',() => { 
 
    document.body.style.backgroundColor = 'yellow'; 
 
}); 
 

 
document.getElementById('button').addEventListener('mouseleave',() => { 
 
    document.body.style.backgroundColor = 'white'; 
 
});
<button id="button">Button</button>

0

私は「それがクリックされています場合ではない」あなたは何を意味するかわからないんだけど、何これは?

<button id="theButton">Press Me</button> 

<script> 
$('#theButton') 
    .on('mouseenter', function(event) { 
     $('body').css('background-color', 'blue'); 
    }) 
    .on('mouseleave', function(event) { 
     $('body').css('background-color', 'yellow'); 
    }); 
</script> 
0

mouseenterとmouseleaveを追加するだけです。それは最も簡単で良いソリューションです。 Mousedownとクリックされた瞬間。これが動作しない理由を

document.getElementById('b1').addEventListener('mouseenter',() => { 
 
    document.body.style.backgroundColor = '#A00'; 
 
}); 
 

 
document.getElementById('b1').addEventListener('mouseleave',() => { 
 
    document.body.style.backgroundColor = '#FFF'; 
 
}); 
 

 

 
document.getElementById('b1').addEventListener('mouseup',() => { 
 
    document.body.style.backgroundColor = '#A00'; 
 
}); 
 

 
document.getElementById('b1').addEventListener('mousedown',() => { 
 
    document.body.style.backgroundColor = '#FFF'; 
 
});
<button id="b1" type="button">1</button>

よろしく、KJ

関連する問題