简体   繁体   中英

How to make onclick event to div background image?

I created a div in html and assigned a background image to it, and i want to make an onclick event to that photo and don't know how, that's the div :

.add_btn {
background-color: #099;
position: absolute;
height: 35px;
width: 200px;
background-image: url(img/add.png); 
background-repeat: no-repeat;
background-position: center center;
top: 265px;

You didn't give any information about your DOM except that you have an element with that class. It's hard to give a good answer but I'll try.

The following code will attach a function to the onclick events of all the elements with the add_btn class.

document.getElementsByClassName("add_btn").onclick =
    function () { 
        alert("Hello"); 
    };

Background image click is not possible. Because you have a foreground layer. But you can use this JQuery for foreground image click...

$('.className > .Inner_Classname2= > img').click(function(e) {
alert("Ok");    
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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