web 前端5 玩转jquery jquery对象跟DOM对象的互相转换

补充点:jquery对象跟DOM对象的互相转换

 

Dom对象
	document.getElementById('i1')

jQuery对象
	$('#i1')
	
Dom对象 => jQuery对象
	$(document.getElementById('i1'))
	
	
	
	$(document.getElementsTagName('div')[0])
	
	
jQuery对象  =>  Dom对象
	$('div').first()[0]
	

 

  

 

一 jquery简介

1 jquery是什么  

  • jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript高手加入其team
  • jQuery是继prototype之后又一个优秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE,写更少的代码,做更多的事情。
  • 它是轻量级的js(压缩后只有21k) ,这是其它的js库所不及的,它兼容CSS3,还兼容各种浏览器 (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)。
  • jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTML documentsevents、实现动画效果,并且方便地为网站提供AJAX交互。
  • jQuery还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。
  • jQuery能够使用户的html页保持代码和html内容分离,也就是说,不用再在html里面插入一堆js来调用命令了,只需定义id即可。

 

2 什么是jQuery对象?

  • jQuery 对象就是通过jQuery包装DOM对象后产生的对象。
  • jQuery 对象是 jQuery 独有的如果一个对象是 jQuery 对象那么它就可以使用 jQuery 里的方法: $(“#test”).html();

      比如: 

      $("#test").html()   意思是指:获取IDtest的元素内的html代码。其中html()jQuery里的方法 

      这段代码等同于用DOM实现代码: document.getElementById(" test ").innerHTML; 

虽然jQuery对象是包装DOM对象后产生的,但是jQuery无法使用DOM对象的任何方法,同理DOM对象也不能使用jQuery里的方法.乱使用会报错

约定:如果获取的是 jQuery 对象那么要在变量前面加上$. 

var $variable = jQuery 对象

var variable = DOM 对象

基本语法:$(selector).action() 

 

 

写在前面 jquery中的$ 就是JQuery 对象,二者相等 $ = JQuery

    $( )  括号内部的值为 标签元素,得到的结果是 jquery对象,一般是一个集合,加索引取到dom对象

1  jquery的两种循环

1.1 jQuery 对象访问  each(callback)

each(callback)
概述
以每一个匹配的元素作为上下文来执行一个函数。
意味着,每次执行传递进来的函数时,函数中的this关键字都指向一个不同的DOM元素(每次都是一个不同的匹配元素)。而且,在每次执行函数时,都会给函数传递一个表示作为执行环境的元素在匹配的元素集合中所处位置的数字值作为参数(从零开始的整型)。 返回 'false' 将停止循环 (就像在普通的循环中使用 'break')。返回 'true' 跳至下一个循环(就像在普通的循环中使用'continue')。
参数
callbackFunctionV1.0

对于每个匹配的元素所要执行的函数
示例
描述:
迭代两个图像,并设置它们的 src 属性。注意:此处 this 指代的是 DOM 对象而非 jQuery 对象。
HTML 代码:
<img/><img/>
jQuery 代码:
$("img").each(function(i){
   this.src = "test" + i + ".jpg";
 });
结果:
[ <img src="test0.jpg" />, <img src="test1.jpg" /> ]
描述:
如果你想得到 jQuery对象,可以使用 $(this) 函数。
HTML 代码:
<button>Change colors</button>
<span></span> 
<div></div> 
<div></div>

<div></div> 
<div></div>
<div id="stop">Stop here</div> 
<div></div>

<div></div>
<div></div>
jQuery 代码:
$("img").each(function(){
  $(this).toggleClass("example");
});
描述:
你可以使用 'return' 来提前跳出 each() 循环。
HTML 代码:
<button>Change colors</button>
<span></span> 
<div></div> 
<div></div>

<div></div> 
<div></div>
<div id="stop">Stop here</div> 
<div></div>

<div></div>
<div></div>
jQuery 代码:
$("button").click(function () { 
$("div").each(function (index, domEle) { 
  // domEle == this 
  $(domEle).css("backgroundColor", "yellow");  
  if ($(this).is("#stop")) { 
  $("span").text("Stopped at div index #" + index); 
  return false; 
  } 
});
});
jquery对象each 循环

1.2 工具  数组和对象操作jQuery.each(object, [callback])

jQuery.each(object, [callback])
概述
通用例遍方法,可用于例遍对象和数组。
不同于例遍 jQuery 对象的 $().each() 方法,此方法可用于例遍任何对象。回调函数拥有两个参数:第一个为对象的成员或数组的索引,第二个为对应变量或内容。如果需要退出 each 循环可使回调函数返回 false,其它返回值将被忽略。
参数
object,[callback]Object,FunctionV1.0

object:需要例遍的对象或数组。
callback:每个成员/元素执行的回调函数。
示例
描述:
例遍数组,同时使用元素索引和内容。
jQuery 代码:
$.each( [0,1,2], function(i, n){
  alert( "Item #" + i + ": " + n );
});
描述:
例遍对象,同时使用成员名称和变量内容。
jQuery 代码:
$.each( { name: "John", lang: "JS" }, function(i, n){
  alert( "Name: " + i + ", Value: " + n );
});
第二种扩展each

 

 

2  寻找元素(重要的选择器和筛选器)  

 

2.1   选择器

    2.1.1 基本选择器      $("*")  $("#id")   $(".class")  $("element")  $(".class,p,div")

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../jquery-1.9.1.min.js"></script>
</head>
<body>
<div id="notMe"><p>id="notMe"</p></div>
<div id="myDiv">id="myDiv"</div>
<span id="foo:bar">1</span>
<span id="foo[bar]">2</span>
<span id="foo.bar">3</span>
<div class="notMe">div class="notMe"</div>
<div class="myClass">div class="myClass"</div>
<span class="myClass">span class="myClass"</span>

<script>
    // id 选择器
    var x1 = $("#myDiv")  // 默认获取的列表  [ <div id="myDiv">id="myDiv"</div> ]
    x1.each(function () {
        console.log("id 选择器",this)
    })


    var x2 = $("#foo\\[bar\\]") // 重点注意转义。
    x2.each(function () {
        console.log("id 选择器",this)
    })

    // 标签选择器 
    var x3 = $("div") // [ <div>DIV1</div>, <div>DIV2</div> ]
    x3.each(function () {
        console.log("标签选择器 ",this)
    })

    // class 选择器
    var x4 = $(".myClass")  // [ <div class="myClass">div class="myClass"</div>, <span class="myClass">span class="myClass"</span> ]
    x4.each(function () {
        console.log("class 选择器 ",this)
    })
    $("*")/*

    匹配所有元素
    多用于结合上下文来搜索
    */

    // selector1,selector2,selectorN
    /*将每一个选择器匹配到的元素合并后一起返回。
    你可以指定任意多个选择器,并将匹配到的元素合并到一个结果内。
    */
    $("div,span,p.myClass") //[ <div>div</div>, <p class="myClass">p class="myClass"</p>, <span>span</span> ]

</script>



</body>
</html>
基础选择器

    2.1.2层级选择器       $(".outer div")  $(".outer>div")   $(".outer+div")  $(".outer~div")

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../jquery-1.9.1.min.js"></script>
</head>
<body>

<form>
  <label>Name:</label>
  <input name="name" />
  <fieldset>
      <label>Newsletter:</label>
      <input name="newsletter" />
 </fieldset>
</form>
<input name="none" />


<script>
    // 后代选择器 ancestor descendant
    // 在给定的祖先元素下匹配所有的后代元素
    var x1 = $("form input") //[ <input name="name" />, <input name="newsletter" /> ]
    x1.each(function () {
        console.log("后代选择器 ",this)
    })
    // 儿子选择器 在给定的父元素下匹配所有的子元素
    var x2 = $("form > input") //[ <input name="name" /> ]

    // 只要是相邻的即可
    var x3 = $("label + input") //[ <input name="name" />, <input name="newsletter" /> ]

    // 兄弟选择器
    var x4  = $("form ~ input") //[ <input name="none" /> ]



</script>
</body>
</html>
层级

    2.1.3 基本筛选器      $("li:first")  $("li:eq(2)")  $("li:even") $("li:gt(1)")

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../jquery-1.9.1.min.js"></script>
</head>
<body>
<ul>
    <li>list item 1</li>
    <li>list item 2</li>
    <li>list item 3</li>
    <li>list item 4</li>
    <li>list item 5</li>
</ul>

<input name="apple" />
<input name="flower" checked="checked" />
<table>
  <tr><td>Header 1</td></tr>
  <tr><td>Value 1</td></tr>
  <tr><td>Value 2</td></tr>
</table>

<h1>Header 1</h1>
<p>Contents 1</p>
<h2>Header 2</h2>
<p>Contents 2</p>
<button id="run">Run</button><div></div>



<script>
    // first last
    var x1 = $("li:first") //[ <li>list item 1</li> ]

    // not()
    var x2 = $("input:not(:checked)") //[ <input name="apple" /> ]

    // even 偶数

    var x3 = $("tr:even") //[ <tr><td>Header 1</td></tr>, <tr><td>Value 2</td></tr> ]
    // odd 奇数
    var x4 = $("tr:odd")// [ <tr><td>Value 1</td></tr> ]

    // eq 找索引 gt() lt() $("div:lang(en)")
    var x5 = $("tr:eq(1)") //[ <tr><td>Value 1</td></tr> ]
    // :header 匹配如 h1, h2, h3之类的标题元素
     $(":header").css("background", "#EEE"); //[ <h1 style="background:#EEE;">Header 1</h1>, <h2 style="background:#EEE;">Header 2</h2> ]

    // :animated 匹配所有正在执行动画效果的元素
    $("#run").click(function(){
      $("div:not(:animated)").animate({ left: "+=20" }, 1000);
    });

        $("div").click(function(){
      if ( $(this).hasClass("protected") )
        $(this)
          .animate({ left: -10 })
          .animate({ left: 10 })
          .animate({ left: -10 })
          .animate({ left: 10 })
          .animate({ left: 0 });
    });
    // focus

    // :root  html元素







</script>
</body>
</html>
冒号的基本选择器

    2.1.4 属性选择器      $('[id="div1"]')   $('["alex="sb"][id]')

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../jquery-1.9.1.min.js"></script>
</head>
<body>



<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>

<table>
  <tr><td>Value 1</td><td></td></tr>
  <tr><td>Value 2</td><td></td></tr>
</table>

<div><p>Hello</p></div>
<div>Hello again!</div>

<script>
        // contains()  匹配包含给定文本的元素
    var x6 = $("div:contains('John')") //[ <div>John Resig</div>, <div>Malcom John Sinclair</div> ]

    // empty  匹配所有不包含子元素或者文本的空元素
    $("td:empty") //[ <td></td>, <td></td> ]
    //:has(selector)  匹配含有选择器所匹配的元素的元素

    $("div:has(p)").addClass("test"); //[ <div class="test"><p>Hello</p></div> ]


    //:parent  匹配含有子元素或者文本的元素
    $("td:parent") //[ <td>Value 1</td>, <td>Value 2</td> ]  查找所有含有子元素或者文本的 td 元素



</script>
</body>
</html>
内容选择器
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
        <script src="../../jquery-1.9.1.min.js"></script>
</head>
<body>

<table>
  <tr style="display:none"><td>Value 1</td></tr>
  <tr><td>Value 2</td></tr>
</table>

<form>
  <input type="text" name="email" />
  <input type="hidden" name="id" />
</form>

<script>
    // :hidden 匹配所有不可见元素,或者type为hidden的元素
    $("tr:hidden") //[ <tr style="display:none"><td>Value 1</td></tr> ]
    $("input:hidden") //[ <input type="hidden" name="id" /> ]

    //:visible 匹配所有的可见元素
    $("tr:visible")  //[ <tr><td>Value 2</td></tr> ]


</script>


</body>
</html>
可见性
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../jquery-1.9.1.min.js"></script>
</head>
<body>

<div>
  <p>Hello!</p>
</div>
<div id="test2"></div>

<input type="checkbox" name="newsletter" value="Hot Fuzz" />
<input type="checkbox" name="newsletter" value="Cold Fusion" />
<input type="checkbox" name="accept" value="Evil Plans" />
<input name="man-news" />
<input name="milkman" />
<input name="letterman2" />
<input name="newmilk" />

<script>

    //[attribute] 匹配包含给定属性的元素。注意,在jQuery 1.3中,前导的@符号已经被废除!如果想要兼容最新版本,只需要简单去掉@符号即可。
    $("div[id]")  //[ <div id="test2"></div> ]
    //[attribute=value]  匹配给定的属性是某个特定值的元素
    $("input[name='newsletter']").attr("checked", true);  //[ <input type="checkbox" name="newsletter" value="Hot Fuzz" checked="true" />, <input type="checkbox" name="newsletter" value="Cold Fusion" checked="true" /> ]
    //[attribute!=value]  [attribute^=value]


    //[selector1][selector2][selectorN]  复合属性选择器,需要同时满足多个条件时使用。
        $("input[id][name$='man']") //[ <input id="letterman" name="new-letterman" /> ]

    //[attribute*=value]  匹配给定的属性是以包含某些值的元素'
    $("input[name*='man']") //[ <input name="man-news" />, <input name="milkman" />, <input name="letterman2" /> ]



</script>


</body>
</html>
属性

  2.1.5 表单选择器      $("[type='text']")----->$(":text")                    注意只适用于input标签

                                 $("input:checked")

    

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
        <script src="../jquery-1.9.1.min.js"></script>
</head>
<body>

<form>
    <input type="button" value="Input Button"/>
    <input type="checkbox" />

    <input type="file" />
    <input type="hidden" />
    <input type="image" />

    <input type="password" />
    <input type="radio" />
    <input type="reset" />

    <input type="submit" />
    <input type="text" />
    <select><option>Option</option></select>

    <textarea></textarea>
    <button>Button</button>

</form>

<script>
    $(":input") //所有input
    $(":password") //[ <input type="password" /> ]
    $(":checkbox")
</script>
</body>
</html>
表单选择

 

2.2 筛选器

     2.2.1  过滤筛选器

                                     $("li").eq(2)  $("li").first()  $("ul li").hasclass("test")

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../jquery-1.9.1.min.js"></script>
</head>
<body>

<p> This is just a test.</p> <p> So is this</p>
<ul>
    <li>list item 1</li>
    <li>list item 2</li>
    <li>list item 3</li>
    <li>list item 4</li>
    <li>list item 5</li>
</ul>
<form><input type="checkbox" /></form>
<div class="protected"></div><div></div>
<p>Hello</p><p id="selected">Hello Again</p>
<script>
    // eq  获取当前链式操作中第N个jQuery对象,返回jQuery对象,当参数大于等于0时为正向选取,比如0代表第一个,1代表第二个。当参数为负数时为反向选取,比如-1为倒数第一个,具体可以看以下示例。
     // 比 基本选择器的 eq 好,这样可以拼接
    $("p").eq(1) //[ <p> So is this</p> ]
    $("p").eq(-1) //[ <p> So is this</p> ]

    // first() last()
    $("ul li").first() //[ <li>list item 1</li> ]

    // hasClass(class) 检查当前的元素是否含有某个特定的类,如果有,则返回true。 这其实就是 is("." + class)。
    $("div").click(function(){
      if ( $(this).hasClass("protected") )
        $(this)
          .animate({ left: -10 })
          .animate({ left: 10 })
          .animate({ left: -10 })
          .animate({ left: 10 })
          .animate({ left: 0 });
    });

    // is() 括号内可以是回调函数function 获取返回值,需要的是true 或者false
    $("input[type='checkbox']").parent().is("form") // true 由于input元素的父元素是一个表单元素,所以返回true。
    // not(expr|ele|fn) 删除与指定表达式匹配的元素
    $("p").not( $("#selected")[0] ) // 从p元素中删除带有 select 的ID的元素 [ <p>Hello</p> ]

</script>


</body>
</html>
过滤

 

     2.2.2  查找筛选器

                                $("div").children(".test")    $("div").find(".test")  

                                $(".test").next()    $(".test").nextAll()   $(".test").nextUntil()

                                $("div").prev()  $("div").prevAll()  $("div").prevUntil()

                                $(".test").parent()  $(".test").parents()  $(".test").parentUntil() 

                                $("div").siblings()

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../jquery-1.9.1.min.js"></script>
</head>
<body>
<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
<p>Hello</p><p class="selected">Hello Again</p><div><span>And Again</span></div>
<div><span>Hello</span><p class="selected">Hello Again</p><p>And Again</p></div>
<div></div><div></div><div></div><div></div>

<dl>
  <dt>term 1</dt>
  <dd>definition 1-a</dd>
  <dd>definition 1-b</dd>
  <dd>definition 1-c</dd>
  <dd>definition 1-d</dd>

  <dt id="term-2">term 2</dt>
  <dd>definition 2-a</dd>
  <dd>definition 2-b</dd>
  <dd>definition 2-c</dd>

  <dt>term 3</dt>
  <dd>definition 3-a</dd>
  <dd>definition 3-b</dd>
</dl>

<div></div><div></div><div></div><div></div>

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

<div style="width:70%;position:absolute;left:100px;top:100px">
  <div style="margin:50px;background-color:yellow">
     <p>点击下面的按钮可以设置本段落的最近的父(祖先)元素的背景色。</p>
   <div>
</div>
<button>点击这里</button>

<script>

    // children(expr)  儿子查找  find(expr)后代查找  expr用以过滤子元素的表达式
    $("div").children() //[ <span>Hello Again</span> ]
    $("div").children("selected") //[ <p class="selected">Hello Again</p> ]

    //next([expr]) expr 用于筛选的表达式
    /*取得一个包含匹配的元素集合中每一个元素紧邻的后面同辈元素的元素集合。
    这个函数只返回后面那个紧邻的同辈元素,而不是后面所有的同辈元素(可以使用nextAll)。可以用一个可选的表达式进行筛选。*/
    $("p").next() //[ <p>Hello Again</p>, <div><span>And Again</span></div> ]

    $("p").next(".selected") //[ <p class="selected">Hello Again</p> ]

    // nextAll(expr)
    $("div:first").nextAll().addClass("after"); //[ <div class="after"></div>, <div class="after"></div>, <div class="after"></div> ]

    // nextutil()
    /*
    查找当前元素之后所有的同辈元素,直到遇到匹配的那个元素为止。
    如果提供的jQuery代表了一组DOM元素,.nextUntil()方法也能让我们找遍所有元素所在的DOM树,直到遇到了一个跟提供的参数匹配的元素的时候才会停下来。这个新jQuery对象里包含了下面所有找到的同辈元素,但不包括那个选择器匹配到的元素。
    如果没有选择器匹配到,或者没有提供参数,那么跟在后面的所有同辈元素都会被选中。这就跟用没有提供参数的 .nextAll() 效果一样
    */

    $('#term-2').nextUntil('dt').css('background-color', 'red');

    var term3 = document.getElementById("term-3");
    $("#term-1").nextUntil(term3, "dd").css("color", "green");

    // prev prevAll 与next等相反

    $("div:last").prevAll().addClass("before");//[ <div class="before"></div>, <div class="before"></div>, <div class="before"></div> ]

    //parent([expr]) 取得一个包含着所有匹配元素的唯一父元素的元素集合。
    $("p").parent() // [ <div><p>Hello</p><p>Hello</p></div>]
    // parents 不含根
    //parentsUntil 查找当前元素的所有的父辈元素,直到遇到匹配的那个元素为止。
    $('li.item-a').parentsUntil('.level-1')
    .css('background-color', 'red');

    // offsetParent() 返回第一个匹配元素用于定位的父节点。  这返回父元素中第一个其position设为relative或者absolute的元素。此方法仅对可见元素有效。
    $("button").click(function(){
        $("p").offsetParent().css("background-color","red");
    });

    // siblings([expr]) 取得一个包含匹配的元素集合中每一个元素的所有唯一同辈元素的元素集合。可以用可选的表达式进行筛选。
    $("div").siblings(".selected") //[ <p class="selected">Hello Again</p> ]


</script>
</body>
</html>
查找
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../jquery-1.9.1.min.js" ></script>
</head>
<body>
<p>Hello <a href="http://ejohn.org/">John</a>, how are you doing?</p>
<p><span>Hello</span>,how are you?</p>
<iframe src="/index-blank.html" width="300" height="100"></iframe>
<script>

    // contents() 查找匹配元素内部所有的子节点(包括文本节点)。如果元素是一个iframe,则查找文档内容
    $("p").contents().not("[nodeType=1]").wrap("<b/>"); //<p><b>Hello</b> <a href="http://ejohn.org/">John</a>, <b>how are you doing?</b></p>

    $("iframe").contents().find("body").append("I'm in an iframe!");

    // end()
    /*回到最近的一个"破坏性"操作之前。即,将匹配的元素列表变为前一次的状态。
    如果之前没有破坏性操作,则返回一个空集。所谓的"破坏性"就是指任何改变所匹配的jQuery元素的操作。这包括在 Traversing 中任何返回一个jQuery对象的函数--'add', 'andSelf', 'children', 'filter', 'find', 'map', 'next', 'nextAll', 'not', 'parent', 'parents', 'prev', 'prevAll', 'siblings' and 'slice'--再加上 Manipulation 中的 'clone'。*/
    $("p").find("span").end() //[ <p><span>Hello</span> how are you?</p> ]


</script>

</body>
</html>
串联

 

实例 左侧菜单 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jquery 竖向菜单</title>

    <script src="jquery-1.9.1.min.js"></script>
    <script>
//          function show(self){
////              console.log($(self).text())
//              $(self).next().removeClass("hide")
//              $(self).parent().siblings().children(".con").addClass("hide")
//
//          }


    </script>
    <style>
          .menu{
              height: 500px;
              width: 30%;
              background-color: gainsboro;
              float: left;
          }
          .content{
              height: 500px;
              width: 70%;
              background-color: rebeccapurple;
              float: left;
          }
         .title{
             line-height: 50px;
             background-color: #425a66;
             color: forestgreen;}


         .hide{
             display: none;
         }


    </style>
</head>
<body>

<div class="outer">

    <input type="checkbox" id="d1">
    <br>
    <br>

    <div class="menu">
        <div class="item">
            <div class="title" onclick="show(this);">菜单一</div>
            <div class="con">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="show(this);">菜单二</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="show(this);">菜单三</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>

    </div>
    <div class="content"></div>

</div>
<script>
    function show(obj) {
        $(".title").siblings().addClass("hide")
        $(obj).siblings().removeClass("hide")
    }
</script>
</body>
</html>
我写的
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>left_menu</title>

    <script src="js/jquery-2.2.3.js"></script>
    <script>
          function show(self){
//              console.log($(self).text())
              $(self).next().removeClass("hide")
              $(self).parent().siblings().children(".con").addClass("hide")

          }
    </script>
    <style>
          .menu{
              height: 500px;
              width: 30%;
              background-color: gainsboro;
              float: left;
          }
          .content{
              height: 500px;
              width: 70%;
              background-color: rebeccapurple;
              float: left;
          }
         .title{
             line-height: 50px;
             background-color: #425a66;
             color: forestgreen;}


         .hide{
             display: none;
         }


    </style>
</head>
<body>

<div class="outer">
    <div class="menu">
        <div class="item">
            <div class="title" onclick="show(this);">菜单一</div>
            <div class="con">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="show(this);">菜单二</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="show(this);">菜单三</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>

    </div>
    <div class="content"></div>

</div>

</body>
</html>
yuanhao teac
<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8' />
        <link rel="stylesheet" type="text/css" href="common.css" />
        <script type="text/javascript" src='jquery-1.8.2.js'></script>
        <style>
            .hide{
                display: none;
            }

            .container{
                width:300px;
                height: 600px;
                background-color: #ddd;
                border: 1px solid #999;
            }

            .container .title{
                height: 38px;
                font-size: 28px;
                line-height: 38px;
                background-color: orange;
                cursor: pointer;
            }

            .container .body{
                background-color:white;
            }

            .container .body a{
                display:block;
                padding: 10px;
            }
        </style>
    </head>
    <body>
        <div class='container'>
            <div>
                <div class='title'>Menu1</div>
                <div class='body'>
                    <a href="">content1</a>
                    <a href="">content2</a>
                    <a href="">content3</a>
                </div>
            </div>

            <div>
                <div class='title'>Menu1</div>
                <div class='body hide'>
                    <a href="">content1</a>
                    <a href="">content2</a>
                    <a href="">content3</a>
                </div>
            </div>

            <div>
                <div class='title'>Menu1</div>
                <div class='body hide'>
                    <a href="">content1</a>
                    <a href="">content2</a>
                    <a href="">content3</a>
                </div>
            </div>
            
            <div>
                <div class='title'>Menu1</div>
                <div class='body hide'>
                    <a href="">content1</a>
                    <a href="">content2</a>
                    <a href="">content3</a>
                </div>
            </div>
            
            <div>
                <div class='title'>Menu1</div>
                <div class='body hide'>
                    <a href="">content1</a>
                    <a href="">content2</a>
                    <a href="">content3</a>
                </div>
            </div>

        </div>

        <script type="text/javascript">
            $(function(){
                $('.title').click(function(){
                    $(this).parent().siblings().children('.body').addClass('hide');
                    $(this).next().removeClass('hide');
                });
            });
        </script>
    </body>
</html>
wusir 实例:左侧菜单

实例 tab切换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>导航内容切换</title>
    <script src="jquery-1.9.1.min.js"></script>
    <style>
        ul{
            list-style: none;
            padding: 0;
            margin: 0;

        }
        ul li{
            float: left;
            /*background-color: #e8e8e8;*/
            color: #1a1c24;
            padding: 8px 10px;
            border: 0.3px solid black;
            border-radius: 4px;
            margin-right: 4px;
        }
        .clear_fix:after{
            display: block;
            content: '.';
            height: 0;
            visibility: hidden;
            clear: both;
        }
        .hide{
            display: none;
        }
        .tab-menu .title{
            background-color: #dddddd;
        }
        .tab-menu .title .active{
            background-color: white;
            color: black;
            border: 0.3px solid red;
            border-radius: 4px;
        }
        .tab-menu .content{
            border: 1px solid #dddddd;
            min-height: 150px;
        }
    </style>

</head>
<body>

    <div style="min-width: 1000px;width: 80%;margin: 0 auto;">
        <div class="tab-menu">
            <div class="title clear_fix">
                <ul class="menu">
                    <li target="h1"  class="active" onclick="Show(this);">价格趋势</li>
                    <li target="h2"  onclick="Show(this);">市场分布</li>
                    <li target="h3" onclick="Show(this);">其他</li>
                </ul>
            </div>
            <div id="content" class="content">
                <div con="h1">content1</div>
                <div con="h3" class="hide">content2</div>
                <div con="h2" class="hide">content3</div>
            </div>
        </div>
    </div>

<script type="text/javascript">
    $(function () {
        $(".menu").delegate("li","click",function () {
            console.log($(this)[0])
            $(this).addClass("active").siblings().removeClass("active");
            var i_d=$(this).attr("target")
            console.log(i_d)
            $("#content").children().each(function () {
                if ($(this).attr("con") == i_d){
                    console.log($(this).attr("con"))
                    $(this).removeClass("hide")
                }else {
                    $(this).addClass("hide")
                }
            })
        })

    })

 // js 方法
    function Show(obj) {
//           var fa_con = obj.getAttribute("target")
//           var sons = obj.parentElement.children;
//           for (var i=0;i<sons.length;i++){
////               sons[i].className = ""
//               if (obj != sons[i]){
//                    sons[i].className = ""
////                   sons[i].removeAttribute("class")
//               }else {
//                  obj.className = "active"
//               }
//           };
////        obj.className = 'active'
//          var conte = document.getElementById("content").children;
//          for (var j=0;j<conte.length;j++){
//              var val_con = conte[j].getAttribute("con")
//              if (val_con == fa_con){
//                    conte[j].classList.remove("hide")
//              }else {
//                  conte[j].className = "hide"
//              }
//
//          }
    }


</script>
</body>
</html>
我写的
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tab</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>
           function tab(self){
               var index=$(self).attr("xxx")
               $("#"+index).removeClass("hide").siblings().addClass("hide")
               $(self).addClass("current").siblings().removeClass("current")

           }
    </script>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .tab_outer{
            margin: 0px auto;
            width: 60%;
        }
        .menu{
            background-color: #cccccc;
            /*border: 1px solid red;*/
            line-height: 40px;
        }
        .menu li{
            display: inline-block;
        }
        .menu a{
            border-right: 1px solid red;
            padding: 11px;
        }
        .content{
            background-color: tan;
            border: 1px solid green;
            height: 300px;
        }
        .hide{
            display: none;
        }

        .current{
            background-color: darkgray;
            color: yellow;
            border-top: solid 2px rebeccapurple;
        }
    </style>
</head>
<body>
      <div class="tab_outer">
          <ul class="menu">
              <li xxx="c1" class="current" onclick="tab(this);">菜单一</li>
              <li xxx="c2" onclick="tab(this);">菜单二</li>
              <li xxx="c3" onclick="tab(this);">菜单三</li>
          </ul>
          <div class="content">
              <div id="c1">内容一</div>
              <div id="c2" class="hide">内容二</div>
              <div id="c3" class="hide">内容三</div>
          </div>

      </div>
</body>
</html>
yuanhao teac

3   操作元素(属性 CSS 和 文档处理)  

3.1 属性操作

     $("p").text()    $("p").html()   $(":checkbox").val()

      $(".test").attr("alex")   $(".test").attr("alex","sb") 

      $(".test").attr("checked","checked")  $(":checkbox").removeAttr("checked")

      $(".test").prop("checked",true)

      $(".test").addClass("hide")

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../jquery-1.9.1.min.js"></script>
</head>
<body>


    <script>

        // html([val|fn])
        $('p').html();
        $("p").html("Hello <b>world</b>!");
        $("p").html(function(n){
        return "这个 p 元素的 index 是:" + n;
        });

        // text()  text([val|fn]) 取得所有匹配元素的内容。
        $('p').text();
        $("p").text("Hello world!");
        $("p").text(function(n){
            return "这个 p 元素的 index 是:" + n;
            });
        // val([val|fn|arr])
        $("input").val();
        $("input").val("hello world!");
        $('input:text.items').val(function() {
          return this.value + ' ' + this.className;
        });


    </script>
</body>
</html>
html text val
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../jquery-1.9.1.min.js"></script>
</head>
<body>

<p> </p>
<script>

    // attr(name|properties|key,value|fn)  设置或返回被选元素的属性值。
    // 建议用prop修改属性,因为attr不能改回来 对于input
    $("img").attr("src");
    $("img").attr({ src: "test.jpg", alt: "Test Image" }); //为所有图像设置src和alt属性。
    $("img").attr("src","test.jpg"); //为所有图像设置src属性。
    $("img").attr("title", function() { return this.src }); //把src属性的值设置为title属性的值。
    //removeAttr(name)
    /*从每一个匹配的元素中删除一个属性
1.6以下版本在IE6使用JQuery的removeAttr方法删除disabled是无效的。解决的方法就是使用$("XX").prop("disabled",false);
1.7版本在IE6下已支持删除disabled。*/


    // prop(name|properties|key,value|fn)
    //选中复选框为true,没选中为false
    $("input[type='checkbox']").prop("checked");
    //禁用页面上的所有复选框。
    $("input[type='checkbox']").prop({
          disabled: true
        });
    //通过函数来设置所有页面上的复选框被选中。
    $("input[type='checkbox']").prop("checked", function( i, val ) {
      return !val;
    });

    // removeProp(name) 用来删除由.prop()方法设置的属性集
    //设置一个段落数字属性,然后将其删除。
    var $para = $("p");
    $para.prop("luggageCode", 1234);
    $para.append("The secret luggage code is: ", String($para.prop("luggageCode")), ". ");
    $para.removeProp("luggageCode");
    $para.append("Now the secret luggage code is: ", String($para.prop("luggageCode")), ". ");
    // The secret luggage code is: 1234. Now the secret luggage code is: undefined.

</script>
</body>
</html>
属性
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../jquery-1.9.1.min.js"></script>
</head>
<body>
<ul>
      <li>Hello</li>
      <li>Hello</li>
      <li>Hello</li>
</ul>
<strong>jQuery 代码:</strong>
<script>

    // addClass(class|fn) addClass 为每个匹配的元素添加指定的类名。
    $("p").addClass("selected");
    $("p").addClass("selected1 selected2");

    $('ul li:last').addClass(function() {
      return 'item-' + $(this).index();
    });

    // removeClass([class|fn])
    $("p").removeClass("selected"); //从匹配的元素中删除 'selected' 类

    //删除匹配元素的所有类
    $("p").removeClass();
    //删除最后一个元素上与前面重复的class
    $('li:last').removeClass(function() {
        return $(this).prev().attr('class');
    });

    //toggleClass(class|fn[,sw]) 如果存在(不存在)就删除(添加)一个类。

    //根据父元素来设置class属性
    $('div.foo').toggleClass(function() {
          if ($(this).parent().is('.bar') {
            return 'happy';
          } else {
            return 'sad';
          }
        });

    //每点击三下加上一次 'highlight' 类
  var count = 0;
  $("p").click(function(){
      $(this).toggleClass("highlight", count++ % 3 == 0);
  });

</script>
</body>
</html>
class css类

实例 返回顶部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>返回顶部</title>
    <script src="jquery-1.9.1.min.js"></script>
    <style>
        .hide{
            display: none;
        }
        .go-top{
            position: fixed;
            right: 10px;
            bottom: 10px;
            width: 40px;
            height: 40px;
            background-color: #5ea593;
            color:black;
        }
        .c1{
            visibility: hidden;
        }
        .go-top:hover .c1{
            visibility: visible;
        }
    </style>
</head>

<body onscroll="Func();">

    <div id="i1" style="height: 2000px">
        sdfsd
        <div id="i3" style="background-color:#e8e8e8;width: 300px;height: 100px;overflow: scroll">
            dfsdf
            <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
            <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
            <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
            <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
            <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
            <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
            <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
        </div>
    </div>

    <div id="i2" class="go-top hide" onclick="goTOP();" >
        <!--<a href="#"></a>  不刷新 下面一样-->
        <a href="javascript:void(0);" class="c1">返回顶部</a>
    </div>
    <script type="text/javascript">
        // jquery
         window.onscroll =  function () {


            var x = $(window).scrollTop()
             console.log(x)
             if (x > 100){
                 $("#i2").removeClass("hide")
             }else {
                 $("#i2").addClass("hide")
             }

         }

        $("#i3").scroll(function () {
             var y=$("#i3").scrollTop()
             console.log(y)
             if (y > 100){
                 $("#i2").removeClass("hide")
             }else {
                 $("#i2").addClass("hide")
             }
        })
        $("#i2").click(function () {
            $(window).scrollTop(0)
            $("#i3").scrollTop(0)
        })

        // js
        function Func() {
//            var hei = document.body.scrollTop;
//            if (hei>100){
//                document.getElementById("i2").classList.remove("hide");
//            }else {
//                document.getElementById("i2").classList.add("hide");
//            };
        };
        function goTOP() {
//            document.body.scrollTop = 0;
        }


    </script>
</body>
</html>
我的
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>


          window.onscroll=function(){

              var current=$(window).scrollTop();
              console.log(current)
              if (current>100){

                  $(".returnTop").removeClass("hide")
              }
              else {
              $(".returnTop").addClass("hide")
          }
          }


           function returnTop(){
//               $(".div1").scrollTop(0);

               $(window).scrollTop(0)
           }




    </script>
    <style>
        body{
            margin: 0px;
        }
        .returnTop{
            height: 60px;
            width: 100px;
            background-color: darkgray;
            position: fixed;
            right: 0;
            bottom: 0;
            color: greenyellow;
            line-height: 60px;
            text-align: center;
        }
        .div1{
            background-color: orchid;
            font-size: 5px;
            overflow: auto;
            width: 500px;
        }
        .div2{
            background-color: darkcyan;
        }
        .div3{
            background-color: aqua;
        }
        .div{
            height: 300px;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
     <div class="div1 div">
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>

     </div>
     <div class="div2 div"></div>
     <div class="div3 div"></div>
     <div class="returnTop hide" onclick="returnTop();">返回顶部</div>
</body>
</html>
yuanhao teac

3.2 CSS操作

        3.2.1(样式)   css("{color:'red',backgroud:'blue'}") 

        3.2.2(位置)   offset()    position()  scrollTop()  scrollLeft()    

        3.2.3(尺寸)   height()  width()  

实例 滚动菜单 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            margin: 0;
            background-color: #dddddd;
        }
        .w{
            margin: 0 auto;
            width: 980px;
        }
        .pg-header{
            background-color: black;
            color: white;
            height: 48px;
        }
        .pg-body .menu{
            position: absolute;
            left: 200px;
            width: 180px;
            background-color: white;
            float: left;
        }
        .pg-body .menu .active{
            background-color: #425a66;
            color: white;

        }
        .pg-body .fixed{
            position: fixed;
            top: 10px;
        }
        .pg-body .content{
            position: absolute;
            left: 385px;
            right: 200px;
            background-color: white;
            float: left;
        }
        .pg-body .content .item{
            height: 900px;
        }
    </style>
</head>
<body onscroll="Hua();">
    <div class="pg-header">
        <div class="w">

        </div>
    </div>
    <div class="pg-body">
        <div id="menu" class="menu">
            <ul id="ul12">
                <li>第一章</li>
                <li>第二章</li>
                <li>第三章</li>
            </ul>
        </div>
        <div id="content" class="content">
            <div class="item">床前明月管</div>
            <div class="item">疑是地上霜</div>
            <div class="item" style="height: 100px;">我是郭德纲</div>
            <div>sd</div>
        </div>

    </div>

    <script>
        function Hua() {
            var a = document.body.offsetHeight;
            var b = document.getElementById('content').offsetHeight
            var c = document.documentElement.clientHeight; //浏览器当前窗口能看到部分高度  如果开了f12 挡住的部分不算
            var huaGao = document.body.scrollTop; //是除了当前能看到的窗口(f12挡住的不算)大小的滚轮滚动高度
            /*
            document.documentElement.clientHeight;
            346
            document.body.offsetHeight;
            48
            document.getElementById('content').offsetHeight
            1900
            document.body.scrollTop;
            1602
            */
            var caiDan = document.getElementById('menu');
            if(huaGao>48){
                caiDan.classList.add('fixed');
            }else{
                caiDan.classList.remove('fixed');
                var active_chi = document.getElementById("ul12").children;
                for (var j=0;j<active_chi.length;j++){
                    active_chi[j].className = ""
                            }
            }

            var items = document.getElementById('content').children;
            for(var i=0;i<items.length;i++){
                var currentItem = items[i];
                var currentItemBodyTop = currentItem.offsetTop + currentItem.offsetParent.offsetTop;
                var currentItemWindowTop = currentItemBodyTop - huaGao;
                console.log(currentItemWindowTop);
                var currentHeight = currentItem.offsetHeight;
                var bottomHeight = currentItemBodyTop+currentHeight;

                console.log((a+b),(c+huaGao))
                if ((a+b) == (c+huaGao)){
                    var mu = document.getElementById('menu').children[0].lastElementChild;
                    var lis = document.getElementById("menu").getElementsByTagName("li");
                    for (var m=0;m<lis.length;m++){
                        var current_list = lis[m];
                        if (current_list.getAttribute("class") == "active"){
                            current_list.classList.remove("active");
                            break;
                        };
                    };
                    mu.classList.add("active")
                    return
                }

                if(currentItemWindowTop<0 && huaGao < bottomHeight){
                    var ziJi = caiDan.getElementsByTagName('li')[i];
                    ziJi.className = 'active';
                    var lis = caiDan.getElementsByTagName('li');
                    for(var j = 0;j<lis.length;j++){
                        if (ziJi == lis[j]){

                        }else {
                            lis[j].classList.remove('active');
                        }
                    }
                    break;

                }


            }



        }
    </script>
</body>
</html>
js 方式

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>

        body{
            margin: 0px;
        }
        img {
            border: 0;
        }
        ul{
            padding: 0;
            margin: 0;
            list-style: none;
        }
        .clearfix:after {
            content: ".";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }

        .wrap{
            width: 980px;
            margin: 0 auto;
        }

        .pg-header{
            background-color: #303a40;
            -webkit-box-shadow: 0 2px 5px rgba(0,0,0,.2);
            -moz-box-shadow: 0 2px 5px rgba(0,0,0,.2);
            box-shadow: 0 2px 5px rgba(0,0,0,.2);
        }
        .pg-header .logo{
            float: left;
            padding:5px 10px 5px 0px;
        }
        .pg-header .logo img{
            vertical-align: middle;
            width: 110px;
            height: 40px;

        }
        .pg-header .nav{
            line-height: 50px;
        }
        .pg-header .nav ul li{
            float: left;
        }
        .pg-header .nav ul li a{
            display: block;
            color: #ccc;
            padding: 0 20px;
            text-decoration: none;
            font-size: 14px;
        }
        .pg-header .nav ul li a:hover{
            color: #fff;
            background-color: #425a66;
        }
        .pg-body{

        }
        .pg-body .catalog{
            position: absolute;
            top:60px;
            width: 200px;
            background-color: #fafafa;
            bottom: 0px;
        }
        .pg-body .catalog.fixed{
            position: fixed;
            top:10px;
        }

        .pg-body .catalog .catalog-item.active{
            color: #fff;
            background-color: #425a66;
        }

        .pg-body .content{
            position: absolute;
            top:60px;
            width: 700px;
            margin-left: 210px;
            background-color: #fafafa;
            overflow: auto;
        }
        .pg-body .content .section{
            height: 500px;
        }
    </style>
</head>
<body>

    <div class="pg-header">
        <div class="wrap clearfix">
            <div class="logo">
                <a href="#">
                    <img src="images/3.jpg">
                </a>
            </div>
            <div class="nav">
                <ul>
                    <li>
                        <a  href="#">首页</a>
                    </li>
                    <li>
                        <a  href="#">功能一</a>
                    </li>
                    <li>
                        <a  href="#">功能二</a>
                    </li>
                </ul>
            </div>

        </div>
    </div>
    <div class="pg-body">
        <div class="wrap">
            <div class="catalog">
                <div class="catalog-item" auto-to="function1"><a>第1张</a></div>
                <div class="catalog-item" auto-to="function2"><a>第2张</a></div>
                <div class="catalog-item" auto-to="function3"><a>第3张</a></div>
            </div>
            <div class="content">

                <div menu="function1" class="section">
                    <h1>第一章</h1>
                </div>
                <div menu="function2" class="section">
                    <h1>第二章</h1>
                </div>
                <div menu="function3" class="section">
                    <h1>第三章</h1>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript" src="js/jquery-2.2.3.js"></script>
    <script type="text/javascript">


     window.onscroll=function(){
         var ws=$(window).scrollTop()
         if (ws>50){
             $(".catalog").addClass("fixed")
         }
         else {
             $(".catalog").removeClass("fixed")
         }
         $(".content").children("").each(function(){

          var offtop=$(this).offset().top;
//             console.log(offtop)
             var total=$(this).height()+offtop;

             if (ws>offtop && ws<total){

                 if($(window).height()+$(window).scrollTop()==$(document).height()){
                     var index=$(".catalog").children(" :last").css("fontSize","40px").siblings().css("fontSize","12px")
                     console.log(index)
                 target='div[auto-to="'+index+'"]';
                 $(".catalog").children(target).css("fontSize","40px").siblings().css("fontSize","12px")

                 }
                 else{
                      var index=$(this).attr("menu");
                 target='div[auto-to="'+index+'"]';
                 $(".catalog").children(target).css("fontSize","40px").siblings().css("fontSize","12px")
                 }


             }

         })

     }

    </script>


</body>
</html>
yuanhao teac

 

3.3 文档处理

      内部插入  $("#c1").append("<b>hello</b>")     $("p").appendTo("div")

                   prepend()    prependTo()

      外部插入  before()  insertBefore()  after insertAfter()

                     replaceWith()   remove()  empty()  clone()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
            <div class="outer">
                <div class="condition">

                        <div class="icons" style="display:inline-block">
                            <a onclick="add(this);"><button>+</button></a>
                        </div>

                        <div class="input" style="display:inline-block">
                            <input type="checkbox">
                            <input type="text" value="alex">
                        </div>
                </div>
            </div>

<script src="jquery-1.9.1.min.js"></script>
    <script>

            function add(self){
                var $duplicate = $(self).parent().parent().clone();
                $duplicate.find('a[onclick="add(this);"]').attr('onclick',"removed(this)").children("").text("-");
                $duplicate.appendTo($(self).parent().parent().parent());

            }
           function removed(self){

               $(self).parent().parent().remove()

           }

    </script>
</body>
</html>
添加项目 减去项目
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>add</title>
    <script src="jquery-1.9.1.min.js"></script>
</head>
<body>

<div class="outer">
    <div class="section" style="display: inline-block;">
        <div class="icons" style="display: inline-block;">
            <a onclick="add(this);"><button>+</button></a>
        </div>
    </div>
    <div class="inputs" style="display: inline-block;">
        <input type="checkbox">
        <input type="text" value="IP">
    </div>
</div>


<script>

    function add(obj) {
        var item = $(obj).parent().parent().parent()
        var num = $("body .outer")
        $(".outer").eq(num.length-1).after(item.clone())
        var nnn = $("body .outer")
         $("body .outer").eq(nnn.length-1).find(":button").text("-")
         $("body .outer").eq(nnn.length-1).find(":button").parent().attr("onclick","remove8(this);") // 修改属性用attr 修改input的状态用prop
//         var xx=$("body .outer").eq(num.length-1).find(":button")[0]
//         console.log(xx)

    }
    function remove8(obj) {
        console.log($(obj).parent().parent()[0])
        $(obj).parent().parent().parent().remove()
    }

</script>

</body>
</html>
我自己写的 自增 删减编辑框

 

3.4 事件

      3.4.1  页面载入

               $(document).ready(function(){}) -----------> $(function(){})

ready(fn)
概述
当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。
这是事件模块中最重要的一个函数,因为它可以极大地提高web应用程序的响应速度。
简单地说,这个方法纯粹是对向window.load事件注册事件的替代方法。通过使用这个方法,可以在DOM载入就绪能够读取并操纵时立即调用你所绑定的函数,而99.99%的JavaScript函数都需要在那一刻执行。
有一个参数--对jQuery函数的引用--会传递到这个ready事件处理函数中。可以给这个参数任意起一个名字,并因此可以不再担心命名冲突而放心地使用$别名。
请确保在 <body> 元素的onload事件中没有注册函数,否则不会触发+$(document).ready()事件。
可以在同一个页面中无限次地使用$(document).ready()事件。其中注册的函数会按照(代码中的)先后顺序依次执行。
参数
fnFunctionV1.0

要在DOM就绪时执行的函数
示例
描述:
在DOM加载完成时运行的代码,可以这样写:
jQuery 代码:
$(document).ready(function(){
  // 在这里写你的代码...
});
描述:
使用 $(document).ready() 的简写,同时内部的 jQuery 代码依然使用 $ 作为别名,而不管全局的 $ 为何。
jQuery 代码:
$(function($) {
  // 你可以在这里继续使用$作为别名...
});
ready(fn)

 

      3.4.2

               $("p").click(function(){})

               $("p").bind("click",function(){})                # 绑定好的。             

               $("ul").delegate("li","click",function(){})  # 可以给单独的元素委托事件,是先点击再绑定的。 可以给li单独的click事件

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../jquery-1.9.1.min.js"></script>
</head>
<body>

<div style="background-color:red">
<p>这是一个段落。</p>
<button>请点击这里</button>
</div>
<script>
    // jquery 事件 click等  bind  delegate委派


    // bind bind(type,[data],fn) 为每个匹配元素的特定事件绑定事件处理函数。
    /*type:含有一个或多个事件类型的字符串,由空格分隔多个事件。比如"click"或"submit",还可以是自定义事件名。
    data:作为event.data属性值传递给事件对象的额外数据对象
    false: 将第三个参数设置为false会使默认的动作失效。*/

    //当每个段落被点击的时候,弹出其文本。

    $("p").bind("click", function(){
      alert( $(this).text() );
    });
    // 同时绑定多个事件类型
    $('#foo').bind('mouseenter mouseleave', function() {
        $(this).toggleClass('entered');
    });

//    同时绑定多个事件类型/处理程序
    $("button").bind({
  click:function(){$("p").slideToggle();},
  mouseover:function(){$("body").css("background-color","red");},
  mouseout:function(){$("body").css("background-color","#FFFFFF");}
});

    //可以在事件处理之前传递一些附加的数据。
   function handler(event) {
      alert(event.data.foo);
    }
    $("p").bind("click", {foo: "bar"}, handler)

    //通过返回false来取消默认的行为并阻止事件起泡。
    $("form").bind("submit", function() { return false; })

    //通过使用 preventDefault() 方法只取消默认的行为。
    $("form").bind("submit", function(event){
      event.preventDefault();
    });
    //通过使用 stopPropagation() 方法只阻止一个事件
    $("form").bind("submit", function(event){
      event.stopPropagation();
    });


    // 事件委派
    //delegate(selector,[type],[data],fn)   用的时候再绑定。
    //指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数。
    //使用 delegate() 方法的事件处理程序适用于当前或未来的元素(比如由脚本创建的新元素)。


    //当点击鼠标时,隐藏或显示 p 元素:
    $("div").delegate("button","click",function(){
      $("p").slideToggle();
    });

    //delegate这个方法可作为live()方法的替代,使得每次事件绑定到特定的DOM元素。
        //以下两段代码是等同的:
    $("table").delegate("td", "hover", function(){
        $(this).toggleClass("hover");
    });
    $("table").each(function(){
        $("td", this).live("hover", function(){
              $(this).toggleClass("hover");
        });

    });




</script>
</body>
</html>
bind delegate live

  

    事件处理 :on off bind trigger

     着重介绍bind 

bind(type,[data],fn)
概述
为每个匹配元素的特定事件绑定事件处理函数。
参数
type,[data],function(eventObject)String,Object,FunctionV1.0

type: 含有一个或多个事件类型的字符串,由空格分隔多个事件。比如"click"或"submit",还可以是自定义事件名。
data:作为event.data属性值传递给事件对象的额外数据对象
fn:绑定到每个匹配元素的事件上面的处理函数
type,[data],false String,Object,boolV1.4.3

type:含有一个或多个事件类型的字符串,由空格分隔多个事件。比如"click"或"submit",还可以是自定义事件名。
data:作为event.data属性值传递给事件对象的额外数据对象
false: 将第三个参数设置为false会使默认的动作失效。
eventsStringV1.4

一个或多个事件类型的字符串和函数的数据映射来执行他们。
示例
描述:
当每个段落被点击的时候,弹出其文本。
jQuery 代码:
$("p").bind("click", function(){
  alert( $(this).text() );
});
描述:
同时绑定多个事件类型
jQuery 代码:
$('#foo').bind('mouseenter mouseleave', function() {
  $(this).toggleClass('entered');
});
描述:
同时绑定多个事件类型/处理程序
jQuery 代码:
$("button").bind({
  click:function(){$("p").slideToggle();},
  mouseover:function(){$("body").css("background-color","red");},  
  mouseout:function(){$("body").css("background-color","#FFFFFF");}  
});
描述:
你可以在事件处理之前传递一些附加的数据。
jQuery 代码:
function handler(event) {
  alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)
描述:
通过返回false来取消默认的行为并阻止事件起泡。
jQuery 代码:
$("form").bind("submit", function() { return false; })
描述:
通过使用 preventDefault() 方法只取消默认的行为。
jQuery 代码:
$("form").bind("submit", function(event){
  event.preventDefault();
});
描述:
通过使用 stopPropagation() 方法只阻止一个事件起泡。
jQuery 代码:
$("form").bind("submit", function(event){
  event.stopPropagation();
});
bind 事件处理

 

    事件委派 delegate  undelegate

delegate(selector,[type],[data],fn)
概述
指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数。
使用 delegate() 方法的事件处理程序适用于当前或未来的元素(比如由脚本创建的新元素)。
参数
selector,[type],fnString,String,FunctionV1.4.2

selector:选择器字符串,用于过滤器触发事件的元素。
type:附加到元素的一个或多个事件。 由空格分隔多个事件值。必须是有效的事件。
fn:当事件发生时运行的函数
selector,[type],[data],fnString,String,Object,FunctionV1.4.2

selector:选择器字符串,用于过滤器触发事件的元素。
type:附加到元素的一个或多个事件。由空格分隔多个事件值。必须是有效的事件。
data:传递到函数的额外数据
fn:当事件发生时运行的函数
selector,eventsString,StringV1.4.3

selector:选择器字符串,用于过滤器触发事件的元素。
events:一个或多个事件类型的字符串和函数的数据映射来执行他们。
示例
描述:
当点击鼠标时,隐藏或显示 p 元素:
HTML 代码:
<div style="background-color:red">
<p>这是一个段落。</p>
<button>请点击这里</button>
</div>
jQuery 代码:
$("div").delegate("button","click",function(){
  $("p").slideToggle();
});
描述:
delegate这个方法可作为live()方法的替代,使得每次事件绑定到特定的DOM元素。
以下两段代码是等同的:
$("table").delegate("td", "hover", function(){
    $(this).toggleClass("hover");
});
$("table").each(function(){
    $("td", this).live("hover", function(){
          $(this).toggleClass("hover");
    });
    
});
delegate

  

    事件切换 hover toggle

hover([over,]out)
概述
一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法。这是一个自定义的方法,它为频繁使用的任务提供了一种“保持在其中”的状态。
当鼠标移动到一个匹配的元素上面时,会触发指定的第一个函数。当鼠标移出这个元素时,会触发指定的第二个函数。而且,会伴随着对鼠标是否仍然处在特定元素中的检测(例如,处在div中的图像),如果是,则会继续保持“悬停”状态,而不触发移出事件(修正了使用mouseout事件的一个常见错误)。
参数
over,outFunction,FunctionV1.0

over:鼠标移到元素上要触发的函数
out:鼠标移出元素要触发的函数
outObjectV1.4

当鼠标移到元素上或移出元素时触发执行的事件函数
示例
over,out 描述:
鼠标悬停的表格加上特定的类
jQuery 代码:
$("td").hover(
  function () {
    $(this).addClass("hover");
  },
  function () {
    $(this).removeClass("hover");
  }
);
out 描述:
hover()方法通过绑定变量"handlerInOut"来切换方法。
jQuery 代码:
$("td").bind("mouseenter mouseleave",handlerInOut);
$("td").hover(handlerInOut);
hover

 

  3.4.3 事件对象 event

        /*
         监听是否已经按下control键
         */
        // jquery 获取ctrl
        window.globalCtrlKeyPress = false;
        $(window).keydown(function (event) {
            var _event = event || window.event
            switch (_event.keyCode){
                    // ...
                    // 不同的按键可以做不同的事情
                    // 不同的浏览器的keycode不同
                    // 更多详细信息:     http://unixpapa.com/js/key.html
                    // 常用keyCode: 空格 32   Enter 13   ESC 27 ctrl 17
                case 17:
                    window.globalCtrlKeyPress = true;

            }
        })
        $(window).keyup(function (event) {
            var _event = event || window.event
            switch (_event.keyCode){
                    // ...
                    // 不同的按键可以做不同的事情
                    // 不同的浏览器的keycode不同
                    // 更多详细信息:     http://unixpapa.com/js/key.html
                    // 常用keyCode: 空格 32   Enter 13   ESC 27 ctrl 17
                case 17:
                    window.globalCtrlKeyPress = false;

            }
        })

         /*
         按下Control,联动表格中正在编辑的select
         */

        function MultiSelect(ths){
            console.log(window.globalCtrlKeyPress)
            console.log($(ths).parent().index())
            if(window.globalCtrlKeyPress){
                var index = $(ths).parent().index();
                var value = $(ths).val();
                $(ths).parent().parent().nextAll().find("td input[type='checkbox']:checked").each(function(){
                    $(this).parent().parent().children().eq(index).children().val(value);
                });
            }
        }
获取不同的按键做不同的事情

dom 的event

<html>
<head>
<script type="text/javascript">
function show_coords(event)
{
x=event.clientX
y=event.clientY
alert("X 坐标: " + x + ", Y 坐标: " + y)
}
</script>
</head>

<body onmousedown="show_coords(event)">

<p>请在文档中点击。一个消息框会提示出鼠标指针的 x 和 y 坐标。</p>

</body>
</html>
dom 的event 获取鼠标的坐标
<html>
<head>
<script type="text/javascript">
function isKeyPressed(event)
{
  if (event.ctrlKey==1)
    {
    alert("The CTRL key was pressed!")
    }
  else
    {
    alert("The CTRL key was NOT pressed!")
    }
  }

</script>
</head>
<body onmousedown="isKeyPressed(event)">

<p>Click somewhere in the document. An alert box will tell you if you pressed the CTRL key or not.</p>

</body>
</html>
dom 的event 鼠标按下德时候检查ctrl有没有被按下

  

可对比 dom事件

http://www.w3school.com.cn/jsref/dom_obj_event.asp

 jquery 事件

注意点

mouseover 跟 mouseenter的区别

前者是不管是指定元素还是其子元素都会触发一次over事件,而后者不管是绑定事件元素还是子元素都只当一次处理

mouseout与mouseleave

不论鼠标指针离开被选元素还是任何子元素,都会触发 mouseout 事件。

只有在鼠标指针离开被选元素时,才会触发 mouseleave 事件。

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">  
x=0;  
y=0;  
$(document).ready(function(){  
  $("div.over").mouseover(function(){  
    $(".over span").text(x+=1);  
  });  
  $("div.enter").mouseenter(function(){  
    $(".enter span").text(y+=1);  
  });  
});  
</script>  
</head>  
<body>  
<p>不论鼠标指针穿过被选元素或其子元素,都会触发 mouseover 事件。</p>  
<p>只有在鼠标指针穿过被选元素时,才会触发 mouseenter 事件。</p>  
<div class="over" style="background-color:lightgray;padding:20px;width:40%;float:left">  
<h2 style="background-color:white;">被触发的 Mouseover 事件:<span></span></h2>  
</div>  
<div class="enter" style="background-color:lightgray;padding:20px;width:40%;float:right">  
<h2 style="background-color:white;">被触发的 Mouseenter 事件:<span></span></h2>  
</div>  
</body>  
</html>  
mouseover和mouseenter区别 

事件对象

    // mousemove([[data],fn]) //mousemove事件处理函数会被传递一个变量——事件对象,其.clientX 和 .clientY 属性代表鼠标的坐标

    $(document).mousemove(function(e){
        var _event = e || window.event
        $("span").text(_event.pageX + ", " + _event.pageY);
    });
View Code
event.pageX
V1.0.4概述
鼠标相对于文档的左边缘的位置。
示例
描述:
显示鼠标相对于文件的左侧和顶部边缘的位置(在iframe中)。
代码:
<!DOCTYPE html>
  <html>
  <head>
    <style>body{ background-color: #eef; }div{ padding: 20px; }</style>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  </head>
  <body>
    <div id="log"></div>
  <script>
   $(document).bind('mousemove',function(e){
       $("#log").text("e.pageX: " + e.pageX + ", e.pageY: " + e.pageY);
   });
 </script>
    </body>
  </html>
鼠标相对于文档的左边缘的位置。

 

实例 拖动面板

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div style="border: 1px solid #ddd;width: 600px;position: absolute;">
        <div id="title" style="background-color: black;height: 40px;color: white;">
            标题
        </div>
        <div style="height: 300px;">
            内容
        </div>
    </div>
<script type="text/javascript" src="jquery-2.2.3.js"></script>
<script>
    $(function(){
        // 页面加载完成之后自动执行
        $('#title').mouseover(function(){
            $(this).css('cursor','move');
        }).mousedown(function(e){
            //console.log($(this).offset());
            var _event = e || window.event;
            // 原始鼠标横纵坐标位置
            var ord_x = _event.clientX;
            var ord_y = _event.clientY;

            var parent_left = $(this).parent().offset().left;
            var parent_top = $(this).parent().offset().top;

            $(this).bind('mousemove', function(e){
                var _new_event = e || window.event;
                var new_x = _new_event.clientX;
                var new_y = _new_event.clientY;

                var x = parent_left + (new_x - ord_x);
                var y = parent_top + (new_y - ord_y);

                $(this).parent().css('left',x+'px');
                $(this).parent().css('top',y+'px');

            })
        }).mouseup(function(){
            $(this).unbind('mousemove');
        });
    })
</script>
</body>
</html>
面板拖动 主要是mousemove等鼠标坐标

放大镜 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>bigger</title>
    <style>
        *{
            margin: 0;
            padding:0;
        }
        .outer{
            height: 350px;
            width: 350px;
            border: dashed 5px cornflowerblue;
        }
        .outer .small_box{
            position: relative;
        }
        .outer .small_box .float{
            height: 175px;
            width: 175px;
            background-color: darkgray;
            opacity: 0.4;
            fill-opacity: 0.4;
            position: absolute;
            display: none;

        }

        .outer .big_box{
            height: 400px;
            width: 400px;
            overflow: hidden;
            position:absolute;
            left: 360px;
            top: 0px;
            z-index: 1;
            border: 5px solid rebeccapurple;
            display: none;


        }
        .outer .big_box img{
            position: absolute;
            z-index: 5;
        }


    </style>
</head>
<body>


        <div class="outer">
            <div class="small_box">
                <div class="float"></div>
                <img src="small.jpg">

            </div>
            <div class="big_box">
                <img src="big.jpg">
            </div>

        </div>


<script src="js/jquery-2.2.3.js"></script>
<script>

    $(function(){

          $(".small_box").mouseover(function(){

              $(".float").css("display","block");
              $(".big_box").css("display","block")

          })
          $(".small_box").mouseout(function(){

              $(".float").css("display","none");
              $(".big_box").css("display","none")

          })



          $(".small_box").mousemove(function(e){

              var _event=e || window.event;

              var float_width=$(".float").width();
              var float_height=$(".float").height();

              console.log(float_height,float_width);

              var float_height_half=float_height/2;
              var float_width_half=float_width/2;
              console.log(float_height_half,float_width_half);


               var small_box_width=$(".small_box").height();
               var small_box_height=$(".small_box").width();



//  鼠标点距离左边界的长度与float应该与左边界的距离差半个float的width,height同理
              var mouse_left=_event.clientX-float_width_half;
              var mouse_top=_event.clientY-float_height_half;

              if(mouse_left<0){
                  mouse_left=0
              }else if (mouse_left>small_box_width-float_width){
                  mouse_left=small_box_width-float_width
              }


              if(mouse_top<0){
                  mouse_top=0
              }else if (mouse_top>small_box_height-float_height){
                  mouse_top=small_box_height-float_height
              }

               $(".float").css("left",mouse_left+"px");
               $(".float").css("top",mouse_top+"px")

               var percentX=($(".big_box img").width()-$(".big_box").width())/ (small_box_width-float_width);
               var percentY=($(".big_box img").height()-$(".big_box").height())/(small_box_height-float_height);

              console.log(percentX,percentY)

               $(".big_box img").css("left", -percentX*mouse_left+"px")
               $(".big_box img").css("top", -percentY*mouse_top+"px")


          })


    })


</script>
</body>
</html>
yuanhao teach
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>放大镜</title>

    <script src="jquery-1.9.1.min.js"></script>
    <style>
        *{
            margin: 0;
            padding:0;
        }
        .outer{
            height: 350px;
            width: 350px;
            border: dashed 5px cornflowerblue;
        }
        .outer .small_box{
            position: relative;
        }
        .outer .small_box .float{
            height: 175px;
            width: 175px;
            background-color: darkgray;
            opacity: 0.4;
            fill-opacity: 0.4;
            position: absolute;
            display: none;

        }

        .outer .big_box{
            height: 400px;
            width: 400px;
            overflow: hidden;
            position:absolute;
            left: 360px;
            top: 0px;
            z-index: 1;
            border: 5px solid rebeccapurple;
            display: none;


        }
        .outer .big_box img{
            position: absolute;
            z-index: 5;
        }


    </style>
</head>
<body>


        <div class="outer">
            <div class="small_box">
                <div class="float"></div>
                <img src="small.jpg">

            </div>
            <div class="big_box">
                <img src="big.jpg">
            </div>

        </div>


<script>
    $(function ($) {
         $(".small_box").mouseover(function(){

              $(".float").css("display","block");
              $(".big_box").css("display","block")

          })
         $(".small_box").mouseout(function(){

              $(".float").css("display","none");
              $(".big_box").css("display","none")

          })

         $(".small_box").mousemove(function (e) {
             var _event = e || window.event;

             var float_width = $(".float").width();
             var float_height = $(".float").height();

             console.log(float_height,float_width)


             var float_width_half = float_width/2;
             var float_height_half = float_height/2;

                var small_box_width=$(".small_box").height();
               var small_box_height=$(".small_box").width();

           var mouse_left=_event.clientX-float_width_half;
              var mouse_top=_event.clientY-float_height_half;

              if(mouse_left<0){
                  mouse_left=0
              }else if (mouse_left>small_box_width-float_width){
                  mouse_left=small_box_width-float_width
              }


              if(mouse_top<0){
                  mouse_top=0
              }else if (mouse_top>small_box_height-float_height){
                  mouse_top=small_box_height-float_height
              }

               $(".float").css("left",mouse_left+"px");
               $(".float").css("top",mouse_top+"px")
               var percentX=($(".big_box img").width()-$(".big_box").width())/ (small_box_width-float_width);
               var percentY=($(".big_box img").height()-$(".big_box").height())/(small_box_height-float_height);

              console.log(percentX,percentY)

               $(".big_box img").css("left", -percentX*mouse_left+"px")
               $(".big_box img").css("top", -percentY*mouse_top+"px")



         })


    })


</script>
</body>
</html>
我的 。 放大镜的 小图 长宽都是大图的一半

 

3.5 动画效果

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../jquery-1.9.1.min.js"></script>
</head>
<body>
<p style="display: none">Hello</p>
<button id="left">«</button> <button id="right">»</button>
<div class="block"></div>
<button id="go"> Run</button>
<div id="block">Hello!</div>

<button id="go1">Go</button> <button id="stop">STOP!</button>
<div class="block"></div><button id="go">Go</button> <button id="stop">STOP!</button>
<div class="block"></div>
<script>
    // show([speed,[easing],[fn]])显示隐藏的匹配元素。
    //这个就是 'show( speed, [callback] )' 无动画的版本。如果选择的元素是可见的,这个方法将不会改变任何东西。无论这个元素是通过hide()方法隐藏的还是在CSS里设置了display:none;,这个方法都将有效。
    $("p").show()

    //用缓慢的动画将隐藏的段落显示出来,历时600毫秒。
    $("p").show("slow");

    //用迅速的动画将隐藏的段落显示出来,历时200毫秒。并在之后执行反馈!
    $("p").show("fast",function(){
       $(this).text("Animation Done!");
     });

    //将隐藏的段落用将近4秒的时间显示出来。。。并在之后执行一个反馈。。

    $("p").show(4000,function(){
       $(this).text("Animation Done...");
     });

    // hide([speed,[easing],[fn]])  隐藏显示的元素
//    这个就是 'hide( speed, [callback] )' 的无动画版。如果选择的元素是隐藏的,这个方法将不会改变任何东西。


    // toggle toggle([speed],[easing],[fn]) 用于绑定两个或多个事件处理器函数,以响应被选元素的轮流的 click 事件。
    //     如果元素是可见的,切换为隐藏的;如果元素是隐藏的,切换为可见的。
    // 如果这个参数为true ,那么匹配的元素将显示;如果false ,元素是隐藏的
    $('#foo').toggle(showOrHide);

    //相当于
    if (showOrHide) {
      $('#foo').show();
    } else {
      $('#foo').hide();
    }

    // 滑动

    // slideDown([speed],[easing],[fn]) 通过高度变化(向下增大)来动态地显示所有匹配的元素,在显示完成后可选地触发一个回调函数。

    // 以滑动方式显示隐藏的 <p> 元素:
    $(".btn2").click(function(){
      $("p").slideDown();
    });
    //用600毫秒缓慢的将段落滑下
    $("p").slideDown("slow");
    //用200毫秒快速将段落滑下,之后弹出一个对话框
    $("p").slideDown("fast",function(){
       alert("Animation Done.");
     });
    // slideUp 同上

    //slideToggle 来回切换
    $("p").slideToggle("fast",function(){
       alert("Animation Done.");
     });

    // 淡入 淡出
    //    fadeIn([speed],[easing],[fn]) 通过不透明度的变化来实现所有匹配元素的淡入效果,并在动画完成后可选地触发一个回调函数。
    //用600毫秒缓慢的将段落淡入
    $("p").fadeIn("slow");

    // fadeOut fadeToggle 同上
    //
    //
    // fadeTo([[speed],opacity,[easing],[fn]])把所有匹配元素的不透明度以渐进方式调整到指定的不透明度,并在动画完成后可选地触发一个回调函数。
    // 这个动画只调整元素的不透明度,也就是说所有匹配的元素的高度和宽度不会发生变化。
    //  opacity:一个0至1之间表示透明度的数字。
    // 用600毫秒缓慢的将段落的透明度调整到0.66,大约2/3的可见度
    $("p").fadeTo("slow", 0.66);
    $("p").fadeTo("fast", 0.25, function(){
       alert("Animation Done.");
     });


    // 自定义
    // animate(params,[speed],[easing],[fn])
    // 在一个动画中同时应用三种类型的效果
    /*用于创建自定义动画的函数。
    这个函数的关键在于指定动画形式及结果样式属性对象。这个对象中每个属性都表示一个可以变化的样式属性(如“height”、“top”或“opacity”)。注意:所有指定的属性必须用骆驼形式,比如用marginLeft代替margin-left.
    而每个属性的值表示这个样式属性到多少时动画结束。如果是一个数值,样式属性就会从当前的值渐变到指定的值。如果使用的是“hide”、“show”或“toggle”这样的字符串值,则会为该属性调用默认的动画形式。
    在 jQuery 1.2 中,你可以使用 em 和 % 单位。另外,在 jQuery 1.2 中,你可以通过在属性值前面指定 "<em>+=</em>" 或 "<em>-=</em>" 来让元素做相对运动。
    jQuery 1.3中,如果duration设为0则直接完成动画。而在以前版本中则会执行默认动画。
    jQuery 1.8中,当你使用CSS属性在css()或animate()中,我们将根据浏览器自动加上前缀(在适当的时候),比如("user-select", "none"); 在Chrome/Safari浏览器中我们将设置为"-webkit-user-select", Firefox会使用"-moz-user-select", IE10将使用"-ms-user-select".*/
    $("#go").click(function(){
      $("#block").animate({
        width: "90%",
        height: "100%",
        fontSize: "10em",
        borderWidth: 10
      }, 1000 );
    });
    // 让指定元素左右移动
    $("#right").click(function(){
      $(".block").animate({left: '+50px'}, "slow");
    });

    $("#left").click(function(){
      $(".block").animate({left: '-50px'}, "slow");
    });

    //一个使用“easein”函数提供不同动画样式的例子。只有使用了插件来提供这个“easein”函数,这个参数才起作用。
    $("p").animate({
       opacity: 'show'
     }, "slow", "easein");

    // stop([clearQueue],[jumpToEnd])停止所有在指定元素上正在运行的动画。
    //如果队列中有等待执行的动画(并且clearQueue没有设为true),他们将被马上执行
    //点击Go之后开始动画,点Stop之后会在当前位置停下来
    // 开始动画
    $("#go1").click(function(){
      $(".block").animate({left: '+200px'}, 5000);
    });

    // 当点击按钮后停止动画
    $("#stop").click(function(){
      $(".block").stop();
    });


    </script>





</body>
</html>
基本 滑动 淡入淡出

实例  隐藏与显示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>
    /**
 * Created by yuan on 16/5/5.
 */

$(document).ready(function(){
    $("#hide").click(function(){
        $("p").hide(1000);
    });
    $("#show").click(function(){
        $("p").show(1000);
    });

//用于切换被选元素的 hide() 与 show() 方法。
    $("#toggle").click(function(){
        $("p").toggle();
    })

 for (var i= 0;i<7;i++){
//            颠倒了常规的$(A).append(B)的操作,即不是把B追加到A中,而是把A追加到B中。
            $("<div>").appendTo(document.body);
        }
        $("div").click(function(){
          $(this).hide(2000);
        });
});

    </script>
    <link type="text/css" rel="stylesheet" href="style.css">
</head>
<body>
    <!--1 隐藏与显示-->
    <!--2 淡入淡出-->
    <!--3 滑动-->
    <!--4 效果-回调:每一个动画执行完毕之后所能执行的函数方法或者所能做的一件事-->


    <p>hello</p>
    <button id="hide">隐藏</button>
    <button id="show">显示</button>
    <button id="toggle">隐藏/显示</button>

</body>
</html>
隐藏与显示

实例  淡入淡出

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>
    $(document).ready(function(){
   $("#in").click(function(){
       $("#id1").fadeIn(1000);
       $("#id2").fadeIn(1000);
       $("#id3").fadeIn(1000);

   });
    $("#out").click(function(){
       $("#id1").fadeOut(1000);
       $("#id2").fadeOut(1000);
       $("#id3").fadeOut(1000);

   });
    $("#toggle").click(function(){
       $("#id1").fadeToggle(1000);
       $("#id2").fadeToggle(1000);
       $("#id3").fadeToggle(1000);

   });
    $("#fadeto").click(function(){
       $("#id1").fadeTo(1000,0.4);
       $("#id2").fadeTo(1000,0.5);
       $("#id3").fadeTo(1000,0);

   });
});

    
    
    </script>

</head>
<body>
      <button id="in">fadein</button>
      <button id="out">fadeout</button>
      <button id="toggle">fadetoggle</button>
      <button id="fadeto">fadeto</button>

      <div id="id1" style="display:none; width: 80px;height: 80px;background-color: blueviolet"></div>
      <div id="id2" style="display:none; width: 80px;height: 80px;background-color: orangered "></div>
      <div id="id3" style="display:none; width: 80px;height: 80px;background-color: darkgreen "></div>

</body>
</html>
淡入淡出

实例  滑动

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>
    $(document).ready(function(){
     $("#flipshow").click(function(){
         $("#content").slideDown(1000);
     });
      $("#fliphide").click(function(){
         $("#content").slideUp(1000);
     });
      $("#toggle").click(function(){
         $("#content").slideToggle(1000);
     })
  });
    </script>
    <style>
        #flipshow,#content,#fliphide,#toggle{
            padding: 5px;
            text-align: center;
            background-color: blueviolet;
            border:solid 1px red;

        }
        #content{
            padding: 50px;
            display: none;
        }
    </style>
</head>
<body>

    <div id="flipshow">出现</div>
    <div id="fliphide">隐藏</div>
    <div id="toggle">toggle</div>

    <div id="content">helloworld</div>

</body>
</html>
slideup 滑动隐藏

实例  回调函数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>

    $(document).ready(function(){
   $("button").click(function(){
       $("p").hide(1000,function(){
           alert('动画结束')
       })

//       $("p").css('color','red').slideUp(1000).slideDown(2000)
   })
});
    </script>
</head>
<body>
  <button>隐藏</button>
  <p>helloworld helloworld helloworld</p>

</body>
</html>
回调函数

实例 京东轮播图

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script src="index.js"></script>
    <script>
        /**
 * Created by yuan on 2016/5/6.
 */

//手动轮播效果
$(function(){
    var size=$(".img li").size()
    for (var i= 1;i<=size;i++){
        var li="<li>"+i+"</li>"
        $(".num").append(li);
    }


    //$(".img li").eq(0).show();
    $(".num li").eq(0).addClass("active");
    $(".num li").mouseover(function(){
       $(this).addClass("active").siblings().removeClass("active");
       var index=$(this).index();
       i=index;
       $(".img li").eq(index).fadeIn(1000).siblings().fadeOut(1000);
   });


i=0;
var t=setInterval(move,1500)

    function move(){
    i++;
    if(i==size){
        i=0;
    }
    $(".num li").eq(i).addClass("active").siblings().removeClass("active");
    $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000);
};

    function moveL(){
    i--;
    if(i==-1){
        i=size-1;
    }
    $(".num li").eq(i).addClass("active").siblings().removeClass("active");
    $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000);
}

    $(".out").hover(function(){
        clearInterval(t);
    },function(){
        t=setInterval(move,1500);
    });

    $(".out .right").click(function(){
        move()
    });
    $(".out .left").click(function(){
       moveL()
    })

});
    </script>
    <link type="text/css" rel="stylesheet" href="style.css">
    <style>
        *{
    margin: 0;
    padding: 0;
}
ul{
    list-style: none;
}

.out{
    width: 730px;
    height: 454px;
    /*border: 8px solid mediumvioletred;*/
    margin: 50px auto;
    position: relative;
}

.out .img li{
    position: absolute;
    left: 0;
    top: 0;
}

.out .num{
    position: absolute;
    left:0;
    bottom: 20px;
    text-align: center;
    font-size: 0;
    width: 100%;
}


.out .btn{
    position: absolute;
    top:50%;
    margin-top: -30px;
    width: 30px;
    height: 60px;
    background-color: aliceblue;
    color: black;
    text-align: center;
    line-height: 60px;
    font-size: 40px;
    display: none;





}

.out .num li{
    width: 20px;
    height: 20px;
    background-color: grey;
    color: #fff;
    text-align: center;
    line-height: 20px;
    border-radius: 50%;
    display: inline;
    font-size: 18px;
    margin: 0 10px;
    cursor: pointer;
}
.out .num li.active{
    background-color: red;
}


.out .left{
    left: 0;
}
.out .right{
    right: 0;
}

.out:hover .btn{
    display: block;
}
    </style>
</head>
<body>
     <div class="out">
         <ul class="img">
             <li><a href="#"><img src="images/1.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/2.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/3.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/4.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/5.jpg" alt=""></a></li>
         </ul>

         <ul class="num">
             <!--<li class="active">1</li>-->
             <!--<li>2</li>-->
             <!--<li>3</li>-->
             <!--<li>4</li>-->
             <!--<li>5</li>-->
         </ul>

         <div class="left btn"><</div>
         <div class="right btn">></div>

     </div>

</body>
</html>
yuanhao teac
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>轮播图</title>
    <script src="jquery-1.9.1.min.js"></script>

        <style>
        *{
            margin: 0;
            padding: 0px;

        }
        ul li{
            list-style: none;
        }
        .outer{
            padding-top: 50px; /* 数字飘下来*/

            height: 454px;
            width: 730px;
            border: solid #9f9f9f 5px;
            border-radius: 6px;
            margin: 0 auto;
            position: relative;
        }
        .num{
            position: absolute;
            left: 0;
            /*top: 0;*/
            bottom: 10px;
            font-size: 0px;
            text-align: center;
            width: 100%;
        }
        .num li{
            height: 20px;
            width: 20px;
            background-color: darkgray;
            border-radius: 60%;
            text-align: center;
            line-height: 20px;
            display: inline-block;
            font-size: 16px;
            margin: 5px;
            cursor: pointer;
        }
        .outer .img li{
            position: absolute;
            left:0 ;
            top: 0;
        }
        .button{
            height: 60px;
            width: 40px;
            background-color: darkgrey;
            position: absolute;
            /*left: 0px;*/
            top: 50%;
            margin-top: -30px;
            opacity: 0.6;
            font-size: 40px;
            font-weight: bolder;
            text-align: center;
            line-height: 60px;
            display: none;
        }
        .btn_right{
            right: 0;
        }
         .outer:hover .button{
             display: block;
             background-color: #00aecd;
             opacity: 0.6;
         }
        .outer .num li.current{
            background-color: red;
        }
        .li_acitve{
                background-color:yellow;
                color:red
            }
    </style>
</head>
<body>

     <div class="outer">
         <ul class="img">
             <li><img src="./img/1.jpg"></li>
             <li><img src="./img/2.jpg"></li>
             <li><img src="./img/3.jpg"></li>
             <li><img src="./img/4.jpg"></li>
             <li><img src="./img/5.jpg"></li>
         </ul>
         <ul class="num">
             <li>1</li>
             <li>2</li>
             <li>3</li>
             <li>4</li>
             <li>5</li>
         </ul>

         <div class="btn_left button"> <  </div>
         <div class="btn_right button"> >  </div>
     </div>


<script>
    x = 0
    $(function ($) {
        f1();
        $(".outer").hover(function () {
            $(".button").css({"color":"red"});

        });

       $(".num li").hover(function () {
             $(this).addClass("li_acitve")
             $(this).siblings().removeClass("li_acitve")
             var inde = $(this).text()
            $(".img").children().eq(inde-1).siblings().fadeOut()
            $(".img").children().eq(inde-1).fadeIn(100)
        })

        $(".num li").click(function () {
            var inde = $(this).text()
            $(".img").children().eq(inde-1).siblings().fadeOut()
            $(".img").children().eq(inde-1).fadeIn(100)
        })


        $(".outer").mouseover(function () {
            clearInterval(t1)
            index_num = $(".num li[class='li_acitve']").text()

        })

        $(".btn_right").click(function () {

            console.log(index_num)
            if (index_num == 5){
                x = 0
            }else {
                x = index_num  //点击就立刻切换
            }
            var inde = $(".num li").eq(x).text()
            $(".num li").eq(x).addClass("li_acitve")
            $(".num li").eq(x).siblings().removeClass("li_acitve")
            $(".img").children().eq(inde-1).siblings().fadeOut()
            $(".img").children().eq(inde-1).fadeIn(100)
            index_num++
            if (index_num >= 5){
                index_num = 0
            }
            console.log(index_num)
        });
        $(".btn_left").click(function () {

            if (index_num == -1){
                x = 0
            }else {
                x = index_num - 2  //点击就立刻切换
            }
            var inde = $(".num li").eq(x).text()
            $(".num li").eq(x).addClass("li_acitve")
            $(".num li").eq(x).siblings().removeClass("li_acitve")
            $(".img").children().eq(inde-1).siblings().fadeOut()
            $(".img").children().eq(inde-1).fadeIn(100)
            index_num--
            if (index_num <= -1){
                index_num = 5
            }
            console.log(index_num)
        })


        $(".outer").mouseout(function () {
            if (index_num == 5){
                x = 0
            }else {
                x = index_num}
            f1();
        })
    })

    function f1() {

        t1 = setInterval(function () {

        var inde = $(".num li").eq(x).text()
        if (inde == 5){
            x = -1
        }
        $(".num li").eq(x).addClass("li_acitve")
        $(".num li").eq(x).siblings().removeClass("li_acitve")
        $(".img").children().eq(inde-1).siblings().fadeOut()
        $(".img").children().eq(inde-1).fadeIn(100)
        x++

        },1000)
    }

</script>
</body>
</html>
我写的 京东轮播图

 

 

3.6 扩展(插件机制)   

  • 1   jquery.extend({})  
  • 2   jquery.fn.extend({})

 

1  jquery对象.扩展方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../jquery-1.9.1.min.js"></script>
</head>
<body>

<script>
    // jQuery.fn.extend(object)
    //增加两个插件方法。
    jQuery.fn.extend({
      check: function() {
        return this.each(function() { this.checked = true; });
      },
      uncheck: function() {
        return this.each(function() { this.checked = false; });
      }
    });
    $("input[type=checkbox]").check();
    $("input[type=radio]").uncheck();

</script>

</body>
</html>
// jQuery.fn.

2  $.扩展方法  

 三元运算 

 return a < b ? a : b; 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../jquery-1.9.1.min.js"></script>
</head>
<body>


<script>
    //jQuery.extend(object)扩展jQuery对象本身。
        //用来在jQuery命名空间上增加新函数。
    // 在jQuery命名空间上增加两个函数。
    jQuery.extend({
      min: function(a, b) { return a < b ? a : b; },  // 三元运算
      max: function(a, b) { return a > b ? a : b; }
    });
    jQuery.min(2,3); // => 2
    jQuery.max(4,5); // => 5
</script>
</body>
</html>
$.扩展

 

实例 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../../s38/jquery-1.9.1.min.js"></script>
    <script>
        $(function () {
            jQuery.fn.extend({
                show1:function () {
                    var ret = this.text();
                    var x = ret+ "sb"
                    return x;
                },
            });

            jQuery.extend({
                show2:function (arg) {
                   var y = $(arg).text()+"sb"
                    return y
                }
            });

            z= $(".title").show1();
            console.log(z);
//            alert(ret);

            ret2 = $.show2(".title");
            console.log(ret2);
        });
    </script>
</head>
<body>
    <div class="title">111</div>
    <div class="title">2222</div>
</body>
</html>
实例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../../s38/jquery-1.9.1.min.js"></script>
</head>
<body>
    <div class="title">1111</div>
    <div class="title">2222</div>
    
    <script>
        $(function () {
            // 定义扩展方式1 : 选择器对象.方法  内部维持字典 用 this
            jQuery.fn.extend({
                f1: function () {
                    // this 是调用f1函数前的选择器对象 $(".title")
                    var txt = this.text(); // 获取选择起对象并在text内部维持循环 txt = 11112222
                    var r = txt + "sb"
                    return r
                }
            })
            var n = $(".title").f1()
            console.log(n)


            // 定义扩展方式2 : $.方法   可以传参数
            jQuery.extend({
                f3: function (arg) {
                    var r1 = $(arg).text() +"sb"
                    return r1
                },
            })

            var ret = jQuery.f3(".title")
            console.log(111,ret)

        })
    </script>
</body>
</html>

  

 

实例 商城菜单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-1.9.1.min.js"></script>
    <style>*{
    margin: 0;
    padding: 0;
}
.hide{
    display:none;
}


.header-nav {
    height: 39px;
    background: #c9033b;
}
.header-nav .bg{
    background: #c9033b;
}

.header-nav .nav-allgoods .menuEvent {
    display: block;
    height: 39px;
    line-height: 39px;
    text-decoration: none;
    color: #fff;
    text-align: center;
    font-weight: bold;
    font-family: 微软雅黑;
    color: #fff;
    width: 100px;
}
.header-nav .nav-allgoods .menuEvent .catName {
    height: 39px;
    line-height: 39px;
    font-size: 15px;
}

.header-nav .nav-allmenu a {
    display: inline-block;
    height: 39px;
    vertical-align: top;
    padding: 0 15px;
    text-decoration: none;
    color: #fff;
    float: left;
}

.header-menu a{
    color:#656565;
}

.header-menu .menu-catagory{
    position: absolute;
    background-color: #fff;
    border-left:1px solid #fff;
    height: 316px;
    width: 230px;
     z-index: 4;
     float: left;
}
.header-menu .menu-catagory .catagory {
    border-left:4px solid #fff;
    height: 104px;
    border-bottom: solid 1px #eaeaea;
}
.header-menu .menu-catagory .catagory:hover {
    height: 102px;
    border-left:4px solid #c9033b;
    border-bottom: solid 1px #bcbcbc;
    border-top: solid 1px #bcbcbc;
}

.header-menu .menu-content .item{
    margin-left:230px;
    position:absolute;
    background-color:white;
    height:314px;
    width:500px;
    z-index:4;
    float:left;
    border: solid 1px #bcbcbc;
    border-left:0;
    box-shadow: 1px 1px 5px #999;
}

    </style>

</head>
<body>
<div class="pg-header">

    <div class="header-nav">
        <div class="container narrow bg">
            <div class="nav-allgoods left">
                <a id="all_menu_catagory" href="#" class="menuEvent">
                    <strong class="catName">全部商品分类</strong>
                    <span class="arrow" style="display: inline-block;vertical-align: top;"></span>
                </a>
            </div>
        </div>
    </div>
    <div class="header-menu">
        <div class="container narrow hide">
            <div id="nav_all_menu" class="menu-catagory">
                <div class="catagory" float-content="one">
                    <div class="title">家电</div>
                    <div class="body">
                        <a href="#">空调</a>
                    </div>
                </div>
                <div class="catagory" float-content="two">
                    <div class="title">床上用品</div>
                    <div class="body">
                        <a href="http://www.baidu.com">床单</a>
                    </div>
                </div>
                <div class="catagory" float-content="three">
                    <div class="title">水果</div>
                    <div class="body">
                        <a href="#">橘子</a>
                    </div>
                </div>
            </div>

            <div id="nav_all_content" class="menu-content">
                <div class="item hide" float-id="one">

                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="勺子">勺子</a> </span>
                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="菜刀">菜刀</a> </span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#">菜板</a> </span>
                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="碗">碗</a> </span>

                        </dd>
                    </dl>

                </div>
                <div class="item hide" float-id="two">
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="">角阀</a> </span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="角阀">角阀</a> </span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="角阀">角阀</a> </span>

                        </dd>
                    </dl>

                </div>
                <div class="item hide" float-id="three">
                    <dl>
                        <dt><a href="#" class="red">厨房用品3</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="角阀">角阀3</a> </span>

                        </dd>
                    </dl>

                    <dl>
                        <dt><a href="#" class="red">厨房用品3</a></dt>
                        <dd>
                            <span>| <a href="http://www.meilele.com/category-jiaofa/" target="_blank" title="角阀">角阀3</a> </span>

                        </dd>
                    </dl>
                </div>
            </div>
        </div>
    </div>

</div>



<script>

    $(function () {
        change("#all_menu_catagory","#nav_all_menu","#nav_all_content")
    })
    function change(menuF,menuS,menuT) {
        $(menuF).bind("mouseover",function () {
            $(menuS).parent().removeClass("hide")
        })
        $(menuF).bind("mouseout",function () {
            $(menuS).parent().addClass("hide")
        });

        $(menuS).children().bind("mouseover",function () {

            $(menuS).parent().removeClass("hide");
            console.log($(this).attr("float-content"))
            $item =$(menuT).find('[float-id="'+$(this).attr("float-content")+'"]');
            console.log($item)
            $item.removeClass("hide").siblings().addClass("hide")
        });
        $(menuS).children().mouseout(function () {
            $(menuS).parent().addClass("hide");
            $(menuT).children().addClass("hide")
        });

        $(menuT).children().mouseover(function () {
            $(menuS).parent().removeClass("hide");
            $(this).removeClass("hide")
        });
        $(menuT).children().mouseout(function () {
            $(menuS).parent().addClass("hide");
            $(this).addClass("hide")
        })


    }


</script>



</body>
</html>
我的
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="X-UA-Compatible" content="IE=8">
    <title>购物商城</title>
    <style>

*{
    margin: 0;
    padding: 0;
}
.hide{
    display:none;
}


.header-nav {
    height: 39px;
    background: #c9033b;
}
.header-nav .bg{
    background: #c9033b;
}

.header-nav .nav-allgoods .menuEvent {
    display: block;
    height: 39px;
    line-height: 39px;
    text-decoration: none;
    color: #fff;
    text-align: center;
    font-weight: bold;
    font-family: 微软雅黑;
    color: #fff;
    width: 100px;
}
.header-nav .nav-allgoods .menuEvent .catName {
    height: 39px;
    line-height: 39px;
    font-size: 15px;
}

.header-nav .nav-allmenu a {
    display: inline-block;
    height: 39px;
    vertical-align: top;
    padding: 0 15px;
    text-decoration: none;
    color: #fff;
    float: left;
}

.header-menu a{
    color:#656565;
}

.header-menu .menu-catagory{
    position: absolute;
    background-color: #fff;
    border-left:1px solid #fff;
    height: 316px;
    width: 230px;
     z-index: 4;
     float: left;
}
.header-menu .menu-catagory .catagory {
    border-left:4px solid #fff;
    height: 104px;
    border-bottom: solid 1px #eaeaea;
}
.header-menu .menu-catagory .catagory:hover {
    height: 102px;
    border-left:4px solid #c9033b;
    border-bottom: solid 1px #bcbcbc;
    border-top: solid 1px #bcbcbc;
}

.header-menu .menu-content .item{
    margin-left:230px;
    position:absolute;
    background-color:white;
    height:314px;
    width:500px;
    z-index:4;
    float:left;
    border: solid 1px #bcbcbc;
    border-left:0;
    box-shadow: 1px 1px 5px #999;
}

    </style>
</head>
<body>

<div class="pg-header">

    <div class="header-nav">
        <div class="container narrow bg">
            <div class="nav-allgoods left">
                <a id="all_menu_catagory" href="#" class="menuEvent">
                    <strong class="catName">全部商品分类</strong>
                    <span class="arrow" style="display: inline-block;vertical-align: top;"></span>
                </a>
            </div>
        </div>
    </div>
    <div class="header-menu">
        <div class="container narrow hide">
            <div id="nav_all_menu" class="menu-catagory">
                <div class="catagory" float-content="one">
                    <div class="title">家电</div>
                    <div class="body">
                        <a href="#">空调</a>
                    </div>
                </div>
                <div class="catagory" float-content="two">
                    <div class="title">床上用品</div>
                    <div class="body">
                        <a href="http://www.baidu.com">床单</a>
                    </div>
                </div>
                <div class="catagory" float-content="three">
                    <div class="title">水果</div>
                    <div class="body">
                        <a href="#">橘子</a>
                    </div>
                </div>
            </div>

            <div id="nav_all_content" class="menu-content">
                <div class="item hide" float-id="one">

                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="勺子">勺子</a> </span>
                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="菜刀">菜刀</a> </span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#">菜板</a> </span>
                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="碗">碗</a> </span>

                        </dd>
                    </dl>

                </div>
                <div class="item hide" float-id="two">
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="">角阀</a> </span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="角阀">角阀</a> </span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="角阀">角阀</a> </span>

                        </dd>
                    </dl>

                </div>
                <div class="item hide" float-id="three">
                    <dl>
                        <dt><a href="#" class="red">厨房用品3</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="角阀">角阀3</a> </span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品3</a></dt>
                        <dd>
                            <span>| <a href="http://www.meilele.com/category-jiaofa/" target="_blank" title="角阀">角阀3</a> </span>

                        </dd>
                    </dl>
                </div>
            </div>
        </div>
    </div>

</div>


<script src="js/jquery-2.2.3.js"></script>

<script type="text/javascript">
    $(document).ready(function () {

        Change_Menu('#all_menu_catagory','#nav_all_menu', '#nav_all_content');

    });



    function Change_Menu(all_menu_catagory,menu, content) {
        $all_menu_catagory = $(all_menu_catagory);
        $menu = $(menu);
        $content = $(content);

        $all_menu_catagory.bind("mouseover", function () {
            $menu.parent().removeClass('hide');
        });
        $all_menu_catagory.bind("mouseout", function () {
            $menu.parent().addClass('hide');
        });

        $menu.children().bind("mouseover", function () {
            $menu.parent().removeClass('hide');
            $item_content = $content.find('div[float-id="' + $(this).attr("float-content") + '"]');
            $item_content.removeClass('hide').siblings().addClass('hide');
        });
        $menu.bind("mouseout", function () {
            $content.children().addClass('hide');
            $menu.parent().addClass('hide');
        });
        $content.children().bind("mouseover", function () {

            $menu.parent().removeClass('hide');
            $(this).removeClass('hide');
        });
        $content.children().bind("mouseout", function () {

            $(this).addClass('hide');
            $menu.parent().addClass('hide');
        });
    }
</script>


</body>
</html>
yuanhao teac

实例 编辑框

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .edit-mode{
            background-color: #b3b3b3;
            padding: 8px;
            text-decoration: none;
            color: white;
        }
        .editing{
            background-color: #f0ad4e;
        }
    </style>
</head>
<body>

    <div style="padding: 20px">
        <input type="button" onclick="CheckAll('#edit_mode', '#tb1');" value="全选" />
        <input type="button" onclick="CheckReverse('#edit_mode', '#tb1');" value="反选" />
        <input type="button" onclick="CheckCancel('#edit_mode', '#tb1');" value="取消" />

        <a id="edit_mode" class="edit-mode" href="javascript:void(0);"  onclick="EditMode(this, '#tb1');">进入编辑模式</a>

    </div>
    <table border="1">
        <thead>
        <tr>
            <th>选择</th>
            <th>主机名</th>
            <th>端口</th>
            <th>状态</th>
        </tr>
        </thead>
        <tbody id="tb1">
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="2" global-key="STATUS">下线</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
            </tr>
        </tbody>
    </table>

    <script type="text/javascript" src="js/jquery-2.2.3.js"></script>
    <script>
        /*
         监听是否已经按下control键
         */
        window.globalCtrlKeyPress = false;

        window.onkeydown = function(event){
            if(event && event.keyCode == 17){
                window.globalCtrlKeyPress = true;
            }
        };
        window.onkeyup = function(event){
            if(event && event.keyCode == 17){
                window.globalCtrlKeyPress = false;
            }
        };

        /*
         按下Control,联动表格中正在编辑的select
         */
        function MultiSelect(ths){
            if(window.globalCtrlKeyPress){
                var index = $(ths).parent().index();
                var value = $(ths).val();
                $(ths).parent().parent().nextAll().find("td input[type='checkbox']:checked").each(function(){
                    $(this).parent().parent().children().eq(index).children().val(value);
                });
            }
        }
    </script>
    <script type="text/javascript">

$(function(){
    BindSingleCheck('#edit_mode', '#tb1');
});

function BindSingleCheck(mode, tb){

    $(tb).find(':checkbox').bind('click', function(){
        var $tr = $(this).parent().parent();
        if($(mode).hasClass('editing')){
            if($(this).prop('checked')){
                RowIntoEdit($tr);
            }else{
                RowOutEdit($tr);
            }
        }
    });
}

function CreateSelect(attrs,csses,option_dict,item_key,item_value,current_val){
    var sel= document.createElement('select');
    $.each(attrs,function(k,v){
        $(sel).attr(k,v);
    });
    $.each(csses,function(k,v){
        $(sel).css(k,v);
    });
    $.each(option_dict,function(k,v){
        var opt1=document.createElement('option');
        var sel_text = v[item_value];
        var sel_value = v[item_key];

        if(sel_value==current_val){
            $(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).attr('selected',true).appendTo($(sel));
        }else{
            $(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).appendTo($(sel));
        }
    });
    return sel;
}

STATUS = [
    {'id': 1, 'value': "在线"},
    {'id': 2, 'value': "下线"}
];

BUSINESS = [
    {'id': 1, 'value': "车上会"},
    {'id': 2, 'value': "二手车"}
];

function RowIntoEdit($tr){
    $tr.children().each(function(){
        if($(this).attr('edit') == "true"){
            if($(this).attr('edit-type') == "select"){
                var select_val = $(this).attr('sel-val');
                var global_key = $(this).attr('global-key');
                var selelct_tag = CreateSelect({"onchange": "MultiSelect(this);"}, {}, window[global_key], 'id', 'value', select_val);
                $(this).html(selelct_tag);
            }else{
                var orgin_value = $(this).text();
                var temp = "<input value='"+ orgin_value+"' />";
                $(this).html(temp);
            }

        }
    });
}

function RowOutEdit($tr){
    $tr.children().each(function(){
        if($(this).attr('edit') == "true"){
            if($(this).attr('edit-type') == "select"){
                var new_val = $(this).children(':first').val();
                var new_text = $(this).children(':first').find("option[value='"+new_val+"']").text();
                $(this).attr('sel-val', new_val);
                $(this).text(new_text);
            }else{
                var orgin_value = $(this).children().first().val();
                $(this).text(orgin_value);
            }

        }
    });
}

function CheckAll(mode, tb){
    if($(mode).hasClass('editing')){

        $(tb).children().each(function(){

            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){

            }else{
                check_box.prop('checked',true);

                RowIntoEdit(tr);
            }
        });

    }else{

        $(tb).find(':checkbox').prop('checked', true);
    }
}

function CheckReverse(mode, tb){

    if($(mode).hasClass('editing')){

        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                check_box.prop('checked',false);
                RowOutEdit(tr);
            }else{
                check_box.prop('checked',true);
                RowIntoEdit(tr);
            }
        });


    }else{
        //
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                check_box.prop('checked',false);
            }else{
                check_box.prop('checked',true);
            }
        });
    }
}

function CheckCancel(mode, tb){
    if($(mode).hasClass('editing')){
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                check_box.prop('checked',false);
                RowOutEdit(tr);

            }else{

            }
        });

    }else{
        $(tb).find(':checkbox').prop('checked', false);
    }
}

function EditMode(ths, tb){
    if($(ths).hasClass('editing')){
        $(ths).removeClass('editing');
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                RowOutEdit(tr);
            }else{

            }
        });

    }else{

        $(ths).addClass('editing');
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                RowIntoEdit(tr);
            }else{

            }
        });

    }
}


    </script>

</body>
</html>
yuanhao teach
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .edit-mode{
            background-color: #b3b3b3;
            padding: 8px;
            text-decoration: none;
            color: white;

        }
        .editing{
            background-color: #f0ad4e;
        }
    </style>
</head>
<body>

    <div style="padding: 20px">
        <input type="button" onclick="CheckAll('#edit_mode', '#tb1');" value="全选" />
        <input type="button" onclick="CheckReverse('#edit_mode', '#tb1');" value="反选" />
        <input type="button" onclick="CheckCancel('#edit_mode', '#tb1');" value="取消" />

        <a id="edit_mode" class="edit-mode" href="javascript:void(0);"  onclick="EditMode(this, '#tb1');">进入编辑模式</a>

    </div>
    <table border="1">
        <thead>
        <tr>
            <th>选择</th>
            <th>主机名</th>
            <th>端口</th>
            <th>状态</th>
        </tr>
        </thead>
        <tbody id="tb1">
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="2" global-key="STATUS">下线</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
            </tr>
        </tbody>
    </table>

    <script type="text/javascript" src="jquery-1.9.1.min.js"></script>
    <script>
        /*
         监听是否已经按下control键
         */
        // jquery 获取ctrl
        window.globalCtrlKeyPress = false;
        $(window).keydown(function (event) {
            var _event = event || window.event
            switch (_event.keyCode){
                    // ...
                    // 不同的按键可以做不同的事情
                    // 不同的浏览器的keycode不同
                    // 更多详细信息:     http://unixpapa.com/js/key.html
                    // 常用keyCode: 空格 32   Enter 13   ESC 27 ctrl 17
                case 17:
                    window.globalCtrlKeyPress = true;

            }
        })
        $(window).keyup(function (event) {
            var _event = event || window.event
            switch (_event.keyCode){
                    // ...
                    // 不同的按键可以做不同的事情
                    // 不同的浏览器的keycode不同
                    // 更多详细信息:     http://unixpapa.com/js/key.html
                    // 常用keyCode: 空格 32   Enter 13   ESC 27 ctrl 17
                case 17:
                    window.globalCtrlKeyPress = false;

            }
        })

         /*
         按下Control,联动表格中正在编辑的select
         */

        function MultiSelect(ths){
            console.log(window.globalCtrlKeyPress)
            console.log($(ths).parent().index())
            if(window.globalCtrlKeyPress){
                var index = $(ths).parent().index();
                var value = $(ths).val();
                $(ths).parent().parent().nextAll().find("td input[type='checkbox']:checked").each(function(){
                    $(this).parent().parent().children().eq(index).children().val(value);
                });
            }
        }

        $(function ($) {
                BindSingleCheck('#edit_mode', '#tb1');

        })

        function BindSingleCheck(obj,tb1) {
            console.log($(tb1 + " :checkbox")[0])//拼接找后代
            $(tb1 +" :checkbox").click(function () {
                console.log(123123131)
                var tr =  $(this).parent().parent(); // 每行tr传过去
                if ($(obj).hasClass("editing")){
                    if ($(this).prop("checked")){
                        RowIntoEdit(tr);
                    }else {
                        RowOutEdit(tr);
                    };
            }
            })

        }


        function CreateSelect(attrs,csses,option_dict,item_key,item_value,current_val){
            var sel = document.createElement("select")
            $.each(attrs,function (k,v) {
                $(sel).attr(k,v) //为select加事件
            });
            $.each(csses,function (k,v) {
                $(sel).attr(k,v);
            });
            $.each(option_dict,function (k,v) {
                var opt = document.createElement("option")
                var sel_val = v[item_key]
                var sel_text = v[item_value]
                if (sel_val == current_val){
                    $(opt).text(sel_text).attr({"value":sel_val,"text":sel_text,"selected":true}).appendTo($(sel));
                }else {
                    $(opt).text(sel_text).attr({"value":sel_val,"text":sel_text,}).appendTo($(sel));
                }
            })
            return sel

        }
        STATUS = [
            {'id': 1, 'value': "在线"},
            {'id': 2, 'value': "下线"}
        ];
        function RowOutEdit($tr) {
            $tr.children().each(function () {
                if ($(this).attr("edit") == "true"){
                    if ($(this).attr("edit-type") == "select"){
                        var new_text = $(this).children().children(":selected").text() // 获取选中的option的text
                        var new_val = $(this).children().val()  // 默认打印选中的option找到select再val就行
                        console.log(new_val)
                        $(this).attr("sel-val",new_val).text(new_text)

                    }else {
                        var text_new_val = $(this).children("input").val()
                        $(this).text(text_new_val)

                    }
                }

            })

        }

        function RowIntoEdit($tr) {
            $tr.children().each(function () {
                if ($(this).attr("edit") == "true"){
//                    console.log($(this).attr("edit-type"))
                    if ($(this).attr("edit-type") == "select"){

                        var select_val = $(this).attr("sel-val");
                        var global_key = $(this).attr('global-key');
                        // 全局环境变量用 window[val] 获取
                        var selelct_tag = CreateSelect({"onchange": "MultiSelect(this);"}, {}, window[global_key], 'id', 'value', select_val);
                        $(this).html(selelct_tag)
                    }else {
                        var text = $(this).text()
                        var temp = "<input value='"+ text+"' />";
                        $(this).html(temp)
                    }
                }
            })
        }

        function EditMode(obj,tb1) {
            if ($(obj).hasClass("editing")){
                $(obj).removeClass("editing")
                $(tb1 + " :checked").each(function () {
                    var tr = $(this).parent().parent();
                    if ($(this).prop("checked")){
//                        console.log(tr[0])
                        RowOutEdit(tr);
                    }else {

                    }
                });
                CheckCancel(obj,tb1)
            }else {
                $(obj).addClass("editing");
                $(tb1 + " :checked").each(function () {
                    var tr =  $(this).parent().parent(); // 每行tr传过去
                    console.log(tr)
                    if ($(this).prop("checked")){
                        console.log(tr[0])
                        RowIntoEdit(tr);
                    }else {

                    }
                });
            };
        }
        function CheckAll(edit_mode,tb1) {
            if ($(edit_mode).hasClass("editing")){
                $(tb1).children().each(function () { // 循环所有tr
                    console.log(this)
                    var tr = $(this);
                    if ($(this).find("input").prop("checked")){

                    }else {
                        $(this).find("input").prop("checked",true)
                        RowIntoEdit(tr);
                    }
                })
            }else {
                $(tb1 + " :checkbox").prop("checked",true)
            }
        }

        function CheckReverse(edit_mode,tb1) {
            if ($(edit_mode).hasClass("editing")){
                $(tb1).children().each(function () { // 循环所有tr
                    console.log(this)
                    var tr = $(this);
                    if ($(this).find("input").prop("checked")){
                        $(this).find("input").prop("checked",false)
                        RowOutEdit(tr);
                    }else {
                        $(this).find("input").prop("checked",true)
                        RowIntoEdit(tr);
                    }
                })
            }else {
                $(tb1 + " :checkbox").each(function () {
//                    console.log($(this).prop("checked"))
                    if ($(this).prop("checked")){
                        $(this).prop("checked",false)
                    } else {
                    $(this).prop("checked",true)
                    }
                })

            }



        }
        function CheckCancel(edit_mode,tb1) {

            if ($(edit_mode).hasClass("editing")){
                console.log(12312321412)
                $(tb1).children().each(function () { // 循环所有tr
                    console.log(this)
                    var tr = $(this);
                    if ($(this).find("input").prop("checked")){
                        $(this).find("input").prop("checked",false)
                        RowOutEdit(tr);
                    }else {

                    }
                })

            }else {
                $(tb1 + " :checkbox").prop("checked",false)
            }
        }



    </script>

</body>
</html>
我写的

 

posted @ 2016-07-20 00:06  众里寻,阑珊处  阅读(430)  评论(0编辑  收藏  举报
返回顶部