开发者

Changing div background color when a link inside the div is clicked

So I have this button that is just actually a div and I have a link inside the d开发者_开发技巧iv

<div id='button'>
    <a href='#'>Link</a>
</div>

I am able to use CSS to change the background color when the link is hovered over. However, how do I make the background color change when the link is clicked? I believe this requires some javascript? If so, can you guys help me with the java script? This is what I came up so far and yet it still does not work.

  <a href="/page/login" onmousedown="document.getElementById('button').backgroundColor='lavender'">login</a>


You can also try using :

<div id='button'>
    <a href='#' onmousedown="this.parentNode.style.backgroundColor='lavender';">Link</a>
</div>

Note that you can use the same code without modifying on any Anchor or other elements as it will be applied to whatever parent object is.


I would controll it with JavaScript and CSS. The following example will toggle the background color of the button with each click. This is done by adding the class clickedto the div, or remove it, if the div has already got this class.

the html code with inline javascript:

<div id="button">
    <a href="#" onmousedown="javascript:(btn=document.getElementById('button')).className = (btn.className  == 'clicked') ? '' : 'clicked';">Link</a>
</div>

the css:

#button {
    background-color: #ccc;
}

#button.clicked {
    background-Color: #123abc;
}


onmousedown="document.getElementById('button').style.backgroundColor='lavender'"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜