jquery插件开发之选项卡制作详解

2020-05-23 06:21:13易采站长站整理

在jquery中,插件开发常见的有:

一种是为$函数本身扩展一个方法,这种是静态扩展(也叫类扩展),这种插件一般是工具方法,

还有一种是扩展在原型对象$.fn上面的,开发出来的插件是用在dom元素上面的

一、类级别的扩展


$.showMsg = function(){
alert('hello,welcome to study jquery plugin dev');
}
// $.showMsg();

注意要提前引入jquery库, 上例在$函数上面添加了一个方法showMsg,那么就可以用$.showMsg()调用了


$.showName = function(){
console.log( 'ghostwu' );
}
$.showName();

这种插件比较少见,一般都是用来开发工具方法,如jquery中的$.trim, $.isArray()等等

二、把功能扩展在$.fn上,

这种插件就是用在元素上,比如,我扩展一个功能,点击按钮,显示当前按钮的值


$.fn.showValue = function(){
return $(this).val();
}

$(function(){
$("input").click(function(){
// alert($(this).showMsg());
alert($(this).showMsg());
});
});

<input type="button" value="点我">

在$.fn上添加一个showValue方法, 返回当前元素的value值. 在获取到页面input元素,绑定事件之后,就可以调用这个方法,显示按钮的值 “点我”,在实际插件开发中,常用的就是这种.接下来,我们就用这种扩展机制开发一个简单的选项卡插件:

页面布局与样式:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/jquery/1.12.0/jquery.js"></script>
<style>
#tab {
width:400px;
height:30px;
}
#tab li, #tab ul {
list-style-type:none;
}
#tab ul {
width:400px;
height: 30px;
border-bottom:1px solid #ccc;
line-height: 30px;
}
#tab ul li {
float:left;
margin-left: 20px;
padding:0px 10px;
}
#tab ul li.active {
background: yellow;
}
#tab ul li a {
text-decoration: none;
color:#666;
}
#tab div {
width:400px;
height:350px;
background-color:#ccc;
}
.clearfix:after{
content: '';
display: block;
clear: both;
height: 0;
visibility: hidden;
}
</style>