简体   繁体   English

jQuery-背景图片点击

[英]Jquery - background-image click

I have a div in the center of the page. 我在页面中央有一个div。 I have the background-image in the body. 我体内有背景图像。 I need to do using jquery click only on the background-image. 我需要使用jquery仅在背景图像上单击。 If you click the div with id divPage, nothing happens. 如果单击ID为divPage的div,则不会发生任何事情。

Thanks for the advice or possibly another solution. 感谢您的建议或可能的其他解决方案。

HTML: HTML:

<body>
    <form id="formBackground" method="post">

        <div id="divPage">
    Text.
        </div>
    </form>
</body>

CSS 的CSS

body{
padding: 0px;
margin: 0px;
font-family: Arial, Verdana, Helvetica, sans-serif;
font-size: 12px;
color: white;
background-image: url('../images/backgrounds/bg.jpg');
background-repeat:no-repeat;
background-position:top;}

div#divPage{
width: 800px;
height: 300px;
margin: auto;}

I tried this, but it does not work correctly: 我试过了,但是不能正常工作:

$('body').click(function() {
            alert("Click");
        })

It was click on the div with id id divPage. 这是在ID为divPage的div上单击的。

You can try: 你可以试试:

$(function () {
  $('body').bind('click', function (evt) {
    if(evt.target == $('body')[0]) {
      console.log('body clicked');
    }
  });
});

Note, if the height of your contents is very low, you'll probably want something like: 请注意,如果内容的高度很低,则可能需要以下内容:

body, html {
  height: 100%;
}

in your css, or there will be no body to be clickable. 在您的CSS中,否则将没有可单击的主体。

Demo: http://jsfiddle.net/mp4TH/ 演示: http//jsfiddle.net/mp4TH/

Untested, but how about something like this: 未经测试,但是这样的事情呢:

$('body').click(function() {
            alert("Click");
        })
$('body>*').click(function(e) {
            e.stopPropagation()
})

Whilst it's not detecting a click on the background image, it does prevent the click action propagating for any element on top of the body. 虽然它没有检测到对背景图像的单击,但确实阻止了单击动作传播到身体顶部的任何元素。 So the click will ONLY be detected on the body itself. 因此,仅在身体本身上会检测到点击。

$('#divPage').click(function(evn) {
    evn.stopPropagation();
});

This is more correct way. 这是更正确的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM