-1

この質問は、私がこのサイトで最後に尋ねたものに関連しています-javascriptを使用してhtmlの背景画像から「リンク」しますか?

うまくいった良い答えを受け取りましたが、背景画像のリンクもコンテナに適用されています。(ID本体の)背景画像をクリックするだけで、コンテナがどのWebサイトにもリンクしないようにするにはどうすればよいですか?

私は十分に明確になっていると思います。よろしくお願いします。

html:

<html>

<head>
<link href = "style1.css" rel = "stylesheet" type = "text/css">
</head>

<div id = "header">
Header
</div>

<body>

<div id = "body">

<div class = "container">

</div>
</div>

</body>

</html>

<script>
document.getElementById('body').onclick = function() {
window.location = 'http://www.google.com/';
}
</script>

CSSコード:

#header{
width:100%;
height:50px;
background-color:black;
}

#body {
width:100%;
height:2000px;
background-image:url('uploads/1.jpg');
cursor:pointer;
}


.container{
 width: 1000px;
margin-right: auto;
margin-left: auto;
height: 1000px;
background-color:white;
}
4

3 に答える 3

2

クリック ハンドラーで、クリックされた要素を確認できます。そうでない場合body(子要素であることを意味します)、何もしません。

document.getElementById('body').onclick = function(e) {
    // e.target is what you clicked on
    // this is always what the event was bound to
    if(e.target === this){
        window.location = 'http://www.google.com/';
    }
}
于 2013-02-05T15:57:36.223 に答える
0

また、falseを返すこともできます

document.getElementById('body').onclick = function(e)
{
    if(!(e.target===this))
        return false;
    console.log("click");
    //window.location = 'http://www.google.com/';
}
于 2013-02-05T16:08:19.043 に答える
0

スクリプトに次のコードを追加してみてください。

document.querySelector('#body .container').onclick = function() {return false; }

持つため:

<script>
document.getElementById('body').onclick = function() {
window.location = 'http://www.google.com/';
}
document.querySelector('#body .container').onclick = function() {return false; }
</script>
于 2013-02-05T15:54:01.677 に答える