简体   繁体   中英

How to make a div clickable

I have a problem, I have around 200 clickable buttons on my website. All Buttons are designed like the same:

<div>
<asp:hyperlink> //or LinkButton
</div>

The Div is the background-style of the button and the Hyperlink / LinkButton is the text of the button. Of course only the Text is clickable right at the moment, so if you click UNDER the Text but ON the Button, you fail with clicking.

I wanna change this, the problem is, what is the fastest and easiest way to be sure the background-button itself is clickable but not writing 200 buttons new?!

Here is a pure CSS solution

Make your tag behave as a block level element and give it the same size as to the parent element.

Here is a jsfiddle

HTML

<div class="wholediv">
    <a href="http://www.google.com">Your link</a>
</div>


CSS

.wholediv{
    width: 100px;
    height: 100px;
    background-color: #efefef;
}

.wholediv a {
    width: 100px;
    height: 100px;
    display:block;
    background-color: pink;
}

I think you can just use:

<div onclick="javascriptFunction()">
Button Text
</div>

You can use jQuery to setup a click event handler for all DIVs, like this:

HTML:

<div style="background-color: red; width: 50px; text-align: center;" id="one">
    <a>Hello</a>
</div>
<br/>
<div style="background-color: yellow; width: 50px; text-align: center;" id="two"> 
    <a>World</a>
</div>

JavaScript:

$("div").click(function (event) {
    alert(event.currentTarget.id);
});

Here is a jsFiddle .

Now to get the server-side logic, you need to have the jQuery click event handler invoke post back to the server via the __doPostBack() , like this:

$("div").click(function (event) {
    __doPostBack(event.currentTarget.id,'');
});

Finally, on the server-side you will need to use the __EVENTTARGET value in the Request object to determine which UI element triggered the post back, like this:

if (IsPostBack)
{
    string ControlID = string.Empty;
    if (!String.IsNullOrEmpty(Request.Form["__EVENTTARGET"]))
    {
        ControlID = Page.Request.Params["__EVENTTARGET"];
        Control postbackControl = Page.FindControl(ControlID);

        // Do something with control, that caused post back, here 
    }
}

You can do it using jQuery. See the following code:

    <div id="button">
         <asp:hyperlink> //or LinkButton
    </div>

    $("#button").click(function (event) {
         // do whatever you want.
    });

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