Heim  >  Artikel  >  Web-Frontend  >  基于JQuery的多标签实现代码_jquery

基于JQuery的多标签实现代码_jquery

WBOY
WBOYOriginal
2016-05-16 17:49:541064Durchsuche

今天要分享的是基于JQuery实现的多标签的切换,JQuery就不用过多介绍了,网上一搜一大堆资料,当然这样的小示例也有很多,这里只是发表一些自己的想法。

下面是本次示例所使用的HTML页面:

复制代码 代码如下:





JQueryProject1










这是内容1

这是内容2

这是内容3






现在的页面还看不出有有标签的效果,所以为了使页面上出现标签效果,给一面添加一个CSS文件:
复制代码 代码如下:

a{
display: block;
text-decoration: none;
color:white;
}
#contenTab ul{
list-style: none;
padding:0px;
margin:0px;
}
#content div.showContent{
line-height:100px;
display: block;
background-color:#B0C4DE;
}
.showTab{
background-color:#B0C4DE;
border-bottom: 1px solid #B0C4DE;
}
div li{
background-color:#5F9EA0;
border-bottom: 1px solid white;
float: left;
border-right: 1px solid white;
color:black;
height:30px;
width:60px;
line-height: 30px;
text-align: center;
}
#content div{
background-color:#B0C4DE;
display:none;
clear: left;
width:300px;
height: 100px;
}

到目前为止页面还只是静态页面,接下来就是最主要的的部分了,这部分就是实现通过鼠标移动来切换标签,实现动态页面,为了达到这个目的需要再添加一个JS文件,当然基于JQuery就必然少不了JQuery的JS文件,本示例使用的是最新的jquery-1.8.1.min.js,可以到JQuery的官网获得,下面是本次示例中实现标签切换的JS代码:
复制代码 代码如下:

$(function(){
$("#contenTab li").each(function(){
var tab = $(this);
var timeoutID;
tab.hover(function(){
timeoutID = setTimeout(function(){
$(".showTab").removeClass("showTab");
$(".showContent").removeClass("showContent");
tab.addClass("showTab");
$($("#content div").get($("#contenTab li").index(tab))).addClass("showContent");
},300);
},function(){
clearTimeout(timeoutID);
});
});
});


到目前为止已经实现了多标签的切换。接下了记录下本次示例的几个注意事项:

1、为了实现当鼠标移到标签(也就是
  • )上让鼠标的形状变成手形,本次示例是通过将
  • 里面的内容放在里面来实现,当然还有跟简单的方法就是给
  • 添加样式cursor: pointer;。

    2、在JS代码中用到了var timeoutID = setTimeout(function,time),这是为了避免鼠标快速移动到来的误操作,time是延时的时间,function里面的就是延时time毫秒过后要执行的内容,也就是说鼠标移到标签上时不会实现立即切换的动作,而是要延时time毫秒过后才会响应切换的动作,如果鼠标在time毫秒之内离开了标签,就会执行clearTimeout(timeoutID),这样time毫秒之后就不会执行function里面的内容,这样就避免了鼠标快速移动带来的误操作。

    今天就到这里了,希望对你会有所帮助。
  • Stellungnahme:
    Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn