开发者

problem with the div tags

开发者 https://www.devze.com 2023-03-29 14:29 出处:网络
I have the following code <HTML> <HEAD> <style type=\"text/css\"> .setbgcolor{ background-color:blue;

I have the following code

<HTML>
<HEAD>
<style type="text/css">
.setbgcolor{
background-color:blue;

}

</style>
<script type="text/javascript">
function setb开发者_如何学JAVAg(id){
document.getElementById(id).className = "setbgcolor";

}
</script>
</HEAD>
<BODY>
<div onclick="setbg(this.id)" id="bgcolor">Label1</div>
<div>Label2</div>
</BODY>
</HTML>

Now, the problem is that- when i click on Label2, background color should be removed from the first div and should get applied to the second div. Can someone help me out?


There is no such event as, perhaps, onunclick in JavaScript; there's blur/onblur, but that requires the element to have had focus before it can be triggered.

That said, working on the assumption that you want only one div to be highlighted at any one time, the following works, albeit you'll have to tailor it to your specific needs:

var buttons = document.getElementsByClassName('button'), curHighlights;

for (i=0; i<buttons.length; i++){
    buttons[i].onclick = function(){
        curHighlights = document.getElementsByClassName('bgcolor');
        if (curHighlights.length) {
            for (h=0; h<curHighlights.length; h++){
                // warning: the following removes _all_ class-names
                curHighlights[h].removeAttribute('class');
            }
        }
            this.className = 'bgcolor';
            this.setAttribute('data-state','1');

    };
}

JS Fiddle demo.

I've removed the onclick event handlers from the in-line html, which makes it a little easier to maintain, although it does look quite messy.

For comparison, however, with jQuery the above could be condensed to:

$('.button').click(
    function(){
        $('.bgcolor').removeClass('bgcolor');
        $(this).addClass('bgcolor');
    });

JS Fiddle demo.


Probably you need something like a variable that stores the previously clicked div.

For example:

var previouslyClickedDiv = null;

function setbg(id){
    if (previouslyClickedDiv) { previouslyClickedDiv.className = ""; }
    var div = document.getElementById(id);
    div.className = "setbgcolor";
    previouslyClickedDiv = div;
}

Of course you can use a shorter variable name!


Try to take a look at jQuery. It will make your life easier.

0

精彩评论

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

关注公众号