在单击javascript时设置超链接样式

Styling hyperlinks on click-javascript

本文关键字:超链接 样式 设置 单击 javascript      更新时间:2023-09-26

嗨,我正在尝试一些东西。单击链接后,我将每个链接的样式(比如背景色)更改为一种不同的颜色,但问题是:我想在点击其他链接时获得链接的原始样式。

HTML代码是:

<a href="#/tab1.html" onclick="hyper1()" class="one" id="link1">Tab1</a>
<a href="#/tab2.html" onclick="hyper2()" class="two" id="link2">Tab2</a>

CSS代码:

a.one{
     left:200px;
}
a.two{
     left:260px;
}
a:link{
     color:white;
     top:20px;
     position: absolute;
     font-weight:bold;
     text-align:center;
     padding:4px;
     text-decoration:none;
}
a:visited{
     font-weight:bold;
     color:#cccccc;
}
a:hover,a:active{
     background-color:rgb(75, 110, 201);
     width: 50px;
}

Javascript代码:

<script>
   function hyper1() {
      var x = document.getElementById("link1");
      x.style.backgroundColor = "rgb(75, 110, 201)";
      x.style.width="50px";
   }
   function hyper2(){
      var y=document.getElementById("link2");
      y.style.backgroundColor="rgb(75, 110, 201)";
      y.style.width="50px";
   }
</script>

我已经更改了您的代码:http://jsfiddle.net/F6kbw/32/如果你有任何问题,请告诉我

function hyper1(element) {
   var x = document.getElementsByTagName("a");
   for (var i = 0;i < x.length;i++) { 
    x[i].style.backgroundColor="white";
   }
   element.style.backgroundColor="rgb(75, 110, 201)";

}

Jquery
// get all links with class .colored_links
var allMyLinks = $(".colored_links");
    allMyLinks.click(function(){
        // regular link color
        var linkRegularColor = "#000000"
        // clicked link color
        var linkClicColor = "#ffffff"
        // set color to all link with class ".colored_links" black color
        allMyLinks.css("color",linkRegularColor);
        // set color of clicked link to white
        $(this).css("color",linkClicColor);
    });

不确定,但你可以试试JS:

var allMyLinks = document.querySelectorAll(".colored_links");
for(var i=0;i<allMyLinks.length;i++){
  allMyLinks[i].addEventListener('click', myFunction, false);
}
var myFunction = function() {
  for(var i=0;i<allMyLinks.length;i++){
    allMyLinks[i].style.color = "#000000";
  }
  this.style.color = "#ffffff";
};