点击另一个

时间:2015-09-03 19:12:20

标签: javascript jquery html css

所以我有这3个蓝色圆圈用于某种导航目的,点击时应该保持红色。当您点击另一个圆圈时,初始的红色圆圈应再次变为蓝色,然后单击的圆圈也将变为红色。

<html>
<head>
<style type='text/css'>

a.link {width: 15px;height: 15px;background-color:blue;border-radius: 50px;position:absolute;}
a.link:hover {background-color: red}
a.link.active {background-color: red;}

.position1 {position: absolute;top: 100px;left: 50%;margin-left: -11.5px;}
.position2 {position: absolute;top: 200px;left: 50%;margin-left: -11.5px;}
.position3 {position: absolute;top: 300px;left: 50%;margin-left: -11.5px;}

</style>
</head>

<body>
<script type='text/javascript'>
            $(function() {
               $('a.link').click(function() {
                   $('a.link').removeClass('active');
                   $(this).addClass('active');
               })
            });
         </script>

  <div class="position1"><a class="link" href="#"></a></div>
  <div class="position2"><a class="link" href="#"></a></div>
  <div class="position3"><a class="link" href="#"></a></div>
</body>
</html>

我过去做过这个,同样的脚本,同样的工作方式但是这是通过使用文本而不是自定义div形状。

我还希望通过使用代码使第二个圆圈从一开始就亮起红色 .eq(1).addClass('active');

这是一个小提琴:https://jsfiddle.net/src6zf67/

2 个答案:

答案 0 :(得分:1)

https://jsfiddle.net/src6zf67/4/

它一直在工作,但你应该onLOad jquery

HTML:

  <div class="position1"><a class="link" href="#"></a></div>
  <div class="position2"><a class="link" href="#"></a></div>
  <div class="position3"><a class="link" href="#"></a></div>

JS:

        $(function() {
           $('a.link').click(function() {
               $('a.link').removeClass('active');
               $(this).addClass('active');
           })
        });

Css:

a.link {width: 15px;height: 15px;background-color:blue;border-radius: 50px;position:absolute;}
a.link:hover {background-color: red}
a.link.active {background-color: red;}

.position1 {position: absolute;top: 100px;left: 50%;margin-left: -11.5px;}
.position2 {position: absolute;top: 200px;left: 50%;margin-left: -11.5px;}
.position3 {position: absolute;top: 300px;left: 50%;margin-left: -11.5px;}

答案 1 :(得分:0)

我希望这有帮助!!祝好运! Here它正在运转。

// Grab all of the links and group them as a single jQuery object.
var $links = $('a.link'); 
// Create an event that triggers when any of the of the links are clicked on.
// Pass to it a data object with a single key $links
// so you can access the other
$links.on( 'click' , { $links : $links } , function ( event ) {
    // Remove the class active from all of the links.
    event.data.$links.removeClass('active');
    // Add the class active to the link we clicked on.
    $( event.target ).addClass( 'active' );
} );