Click on an element highlights other element

倖福魔咒の 提交于 2021-01-27 14:40:46

问题


Is there any way to change the attributes of an element when clicking on another element? For example, consider this approach where I have a link like so:

<a href="#100">Click me!</a>

And then close to it I have this:

<span id="100" class="clickTarget">Important text</span>

And then on my css file I have this:

.clickTarget:target {
    color: #4f8dd5;
}

That means whenever the link is clicked, Important text changes its color. The problem with this approach is that the page is also scrolled even if only a bit. Is there any other way to do this that doesn't scroll the page?

You can use jQuery if you see fit.


回答1:


This will work with multiple links:

change your css to:

.clickTarget.target {
    color: #4f8dd5;
}

give your links a common class ie link

$('a.link').on('click', function() {
   $('.target').removeClass('target');
   var id = $(this).attr('href');
   $(id).addClass('target');
   return false;
});

http://jsfiddle.net/8S5mD/2/




回答2:


Add an attribute data-id (or other names) to your a link to specify the id of the associated span.

<a href="#100" data-id="100">Click me!</a>

And here is javascript:

window.onload = function () {
    var alinks = document.getElementsByTagName('a');
    for (var i = 0; i < alinks.length; i++) {
        alinks[i].addEventListener('click', function () {
            var id = this.getAttribute('data-id');
            var span = document.getElementById(id);
            span.style.color = '#4f8dd5';
        });
    }
}

See example at jsFiddle




回答3:


Suppose something like this should work for you:

CSS:

   .target{
       color:#4f8dd5;
    }   

HTML:

<a href="#" data-target="#100">click me<a>

JS:

$(document).on("click", "a", function(e) {
   if($(this).data("target")) {
     e.preventDefault(); //just to avoid # appearing in address after click.
     $(".target").removeClass("target");
     $($(this).data("target")).addClass("target");
   }
})

This way ANY (even if it was added after code above is executed) link will run a function and if it has a data-target attribute, it will be used as a jquery selector to find an element which should be highlighted.

UPD:

Changed to reflect behavior of target (only one element should be highlighted at once) pointed by David Fregoli




回答4:


Try this one

    $("a").bind('click',function(e){
          if(!$("span.clickTarget").hasClass('changeTextColor')){
             $("span.clickTarget").addClass('changeTextColor');
           }
     });

css:

    .changeTextColor {
         color: #4f8dd5;
    }


来源:https://stackoverflow.com/questions/15702323/click-on-an-element-highlights-other-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!