在单击新按钮时切换链接/按钮颜色

Toggle link/button color on new button click

本文关键字:按钮 链接 颜色 单击 新按钮      更新时间:2023-09-26

我正在尝试将一些定制按钮导入到营销调查应用程序中。我想设置一些按钮样式与CSS和Jquery与一些特定的功能。

我需要让按钮改变外观并停留在点击上。我已经能够使用下面的代码完成这一点。

我需要帮助创建一个函数,返回任何以前选择的按钮到原始状态,同时将新选择的按钮更改为"单击"状态。

详细的帮助将是最感激的!

HTML:

<body>
<a href="#" ID="button">Test Link 1</a><link href="newStyleSheet.css" rel="stylesheet" type="text/css" />
<a href="#" ID="button">Test Link 2</a><link href="newStyleSheet.css" rel="stylesheet" type="text/css" />
<script src="jquery.min.js" type="text/javascript"></script>

<script type="text/javascript">
  $(document).ready(function(){
     $('a').click(function(){
       $ (this).toggleClass('clicked');
     });
  });
</script>
</body>
CSS:

a#button{
    -moz-box-shadow:inset 0px 1px 0px 0px #ffffff;
    -webkit-box-shadow:inset 0px 1px 0px 0px #ffffff;
    box-shadow:inset 0px 1px 0px 0px #ffffff;
    background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ededed), color-stop(1, #dfdfdf) );
    background:-moz-linear-gradient( center top, #ededed 5%, #dfdfdf 100% );
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ededed', endColorstr='#dfdfdf');
    background-color:#ededed;
    -moz-border-radius:6px;
    -webkit-border-radius:6px;
    border-radius:6px;
    border:1px solid #dcdcdc;
    display:inline-block;
    color:#777777;
    font-family:arial;
    font-size:15px;
    font-weight:bold;
    text-decoration:none;
    text-shadow:1px 1px 0px #ffffff;
    width: 160px;
    padding-top: 6px;
    padding-right: 24px;
    padding-bottom: 6px;
    padding-left: 24px;
    text-align: center;
    vertical-align: middle;
    margin-right: 30px;
    margin-left: 30px;
}
a.clicked#button{
    background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #e5c9ab), color-stop(1, #d95936) );
    background:-moz-linear-gradient( center top, #e5c9ab 5%, #d95936 100% );
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#e5c9ab', endColorstr='#d95936');
    background-color:#dfdfdf;
    text-shadow:1px 1px 0px #777777;
    color:#ffffff;
}

首先,您有两个具有相同id的元素;这是无效的HTML: id 必须在文档中是唯一的。如果您希望多个元素共享相同的样式,请使用class -name代替。也就是说,我已经将你的HTML修改为:

<a href="#" class="button">Test Link 1</a>
<a href="#" class="button">Test Link 2</a>

对于jQuery,我建议:

$('a.button').click(function(e){
    e.preventDefault();
    $(this).addClass('clicked').siblings().removeClass('clicked');
});

JS Fiddle demo.

上面的操作假设元素总是兄弟元素;如果它们可能不是:

$('a.button').click(function(e){
    e.preventDefault();
    $('a.clicked').removeClass('clicked');
    $(this).addClass('clicked');
});

JS Fiddle demo.

引用:

  • addClass() .
  • click() .
  • 元素标识符:id和class属性(W3.org)。
  • event.preventDefault() .
  • removeClass() .
  • siblings() .
$(document).ready(function(){
     $('a').click(function(){
         // reset all buttons to un-clicked state
         $('a').removeClass('clicked');
         $(this).toggleClass('clicked');
     });
});