2013-05-25 225 views
0

我正在尝试将一些自定义按钮导入到市场调查应用程序中。我想设置一些带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; 
} 

回答

1

首先,你必须使用相同的id两个元素;这是无效的HTML:一个id必须在文档中是唯一的。如果您想要多个元素共享相同的样式,请改为使用class-名称。这就是说,我已经修改你的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

参考文献:

+0

太棒了,正是我需要的! –

+0

我很高兴得到了帮助! =] –

0
$(document).ready(function(){ 
    $('a').click(function(){ 
     // reset all buttons to un-clicked state 
     $('a').removeClass('clicked'); 
     $(this).toggleClass('clicked'); 
    }); 
});