2017-08-06 12 views
1

なぜif文はここで働いていません。また、のdocument.getElementById(「ID」)style.cursorが期待通りに動作しない

<!DOCTYPE html> 
<html> 
<body> 

<style>#myP{cursor:pointer;}</style> 

<p id="myP">random text</p> 
<button type="button" onclick="myFunction()">alert aaa</button> 

<script> 
function myFunction(){ 
    if(document.getElementById("myP").style.cursor=="pointer"){ 
     alert("aaa"); 
    } 
} 
</script> 

</body> 
</html> 

、私はif文の仕事を作る方法を知りたいです以下のようなリンクにカーソル:

<style>#myP{cursor: url(../randomFolder/cursor.png) 5 8, auto;}</style> 
+3

DOM要素ノードの '.style'プロパティは、「スタイル」属性を介して要素に直接*コード化されたスタイルのみを含みます。 CSSによって適用されるスタイルへのアクセスは提供されません。その情報を取得するには、 'getComputedStyle()'のようなものを使用しなければなりません。 – Pointy

+0

ありがとうございました。 –

答えて

4

ではなく、これを使用します。
if (window.getComputedStyle(document.getElementsByTagName('body')[0]).cursor == 'pointer')

1

.styleは、インラインCSSのために動作します。 window.getComputedStyle()では、非インラインCSSを介して設定されたスタイルを取得できます。あなたは以下を参照することができますように、完全なURLに正規化されるパスを含めているため、リンク画像にカーソルを合わせることは、単に「ポインタ」のような単純な文字列にマッチするよりも少し複雑です、あなたの2番目の質問については

、 ( "https://stacksnippets.net"はCSSに指定されていなくてもパスに含まれています)。完全なカーソル値の部分文字列をテストするのが最善でしょう。したがって、あなたのコードが "yourdomain" .COM」ではなくオン "" www.yourdomain.com:

var myFunction = function() { 
 
    var A = document.getElementById('a'); 
 
    var B = document.getElementById('b'); 
 

 
    console.log(window.getComputedStyle(A).cursor); 
 
    console.log(window.getComputedStyle(B).cursor); 
 

 
    if (window.getComputedStyle(A).cursor == 'pointer') { 
 
    console.log("A matched"); 
 
    } 
 

 
    var bCursor = window.getComputedStyle(B).cursor; 
 
    if (bCursor.indexOf('cursor.png') > -1) { // not hardcoding the full URL here 
 
    console.log("B matched"); 
 
    } 
 
}
#a { 
 
    cursor: pointer 
 
} 
 

 
#b { 
 
    cursor: url(randomFolder/cursor.png) 5 8, auto; 
 
}
<p id="a">random text</p> 
 
<p id="b">more random text</p> 
 
<button onclick="myFunction()">alert</button>

0

jQueryをCSS関数と併用すると、短いコードで必要な種類のカーソルが返されます。

$('#myP').css('cursor') 
関連する問題