【JQuery】基础

爱⌒轻易说出口 提交于 2020-01-16 03:43:30
  • event.pageX;event.pageY, function参数传入event,并返回当前鼠标的位置
$(document).mousemove(function(event){
    $("span").text("X: " + event.pageX + ", Y: " + event.pageY);
});

常用的事件:

  • select(): input 里面的文本被选中
$('input').select(function(){
    alert('selected!')
})


$('input').select();//导致文本内容被选中

  $("input").trigger("select");

$("p").trigger("myPara", [参数1,参数2,参数n]);


bind():被on()替代


on():在被选元素及子元素上添加一个或多个事件处理程序

https://www.runoob.com/jquery/event-on.html

$('div').on(event,  [childSelector],  [data],  function(){})

  • $('div').on('click',function(){})
  • 添加多个事件$('div').on('click  mouseover',function(){})
  • 添加多个事件
$('div').on({
    click:function(){alert('click')},
    mouseover:function(){alert('mouseover')}
})

传入的参数像一个事件映射对象,但是这个对象的value不能有引号
  • 添加自定义事件----传递数组/字符串
array=['nmj','fxp']
$('button').click(function(){
    $('p').trigger('newEvent',array)  //触发p的newEvent事件
})

//事件的绑定
$('p').on('newEvent',function(e,ary){ //第一个参数必须是e
    console.log(ary[0])
    console.log(ary[1])
})
  • 向函数通过e来传递参数----传递一个对象
function myfun(e){
    console.log(e.data.msg)
}
$(document).ready(function(){
    $('div').on('click',{msg:'nmj'},myfun)
})
  • 向未来的元素添加事件(动态添加事件)

https://www.runoob.com/try/try.php?filename=tryjquery_event_on_newel

   不用特意利用事件冒泡就可以动态添加事件:$(父元素).on('click',子元素,function(){})

  • 移出事件用off:$('p').off(事件)
  • one(): 运行一次就自动移除

 


$(document).ready(function(){

         //jq code

})

 window.onload()和$(document).ready区别:前者是html所有的内容都加载之后运行js;后者是DOM加载完就运行jq


($function(){
    $('.btn').click(function(){
        $('p').hide();
    })
})
还有其他一些伪类选择器,最好背一下

$('[href]') //带有href属性的所有元素

$('a[href!='#']') //href!='#'的所有a元素

$(':button')//type=button的input  &&  <button>

jq事件

click(fun)、dblclick(fun);

mouseenter(fun)(划入)、mouseleave(fun)(划出);mousedown(fun)(划入+按下)、mouseup(fun)(鼠标松开);

hover(fun1,fun2)(mouseenter和mouseleave分别代表fun1和fun2)

focus()(获得焦点)、blur()(失去焦点)---->这俩货通常一起用

$('form').submit(fun);(提交)  //  $('button').submit();

mouseover和mouseout区别:mouseenter事件只作用于目标元素,而mouseover最用于目标元素及其子代元素;

$('.input').change(fun)(当表单的value改变时发生(仅适用于表单字段))

$(window).resize();//当浏览器窗口发生变化时

$("div").scroll(fun);  // 当div的滚动条发生滚动时


jq效果

1.  hide()和show()---------display:none;用show()好用,visibility:hidden用show()不好用

    .hide(speed,fun);---->fun时隐藏之后调用的函数;

    .show(speen,fun);

    .toggle(speed,fun);===show+hide

2.  fadeIn()  & fadeOut() & fadeToggle()    ---->(speed,fun)  淡入淡出                             css3可实现,css用的多【待定】

     .fadeTo(speed,opacity,fun)--->设定不透明度opacity:0~1

3.  slideUp() & slideDown() & slideToggle()    ---->(speed,fun)   向下滑动元素---------display:none;用show()好用,visibility:hidden用show()不好用

4.  animate()--->jq动画--->一个元素形成一个动画元素                                                                css3可实现,css用的多【待定】

1.
$("div").animate({
      //css样式
      left:'250px',
      opacity:'0.5',
      height:'+=150px',
      width:'+=150px'
},speed,fun);

注意 :paddingLeft 而不是 padding-left,使用 marginRight 而不是 margin-right

2.
$("div").animate({
    height:'toggle' //"show"、"hide" 或 "toggle" 就和hide等一样的效果
  });

5.停止动画

$("div").stop(); 停止div当前animate,当前div的下一个animate继续进行

$("div").stop(true);停止div所有的animate

$("div").stop(true,true);停止div当前animate,并达到当前animate的最终效果;并不达到所有的animate的所有效果

jq DOM操作

  • text();html();val()

1. $('#test').text();---获得文本文字;.html()获得文本+html标签;.val()--获得表单值

2. 修改直接.text('i hava a pen');同html();val()

3. 回调:

$('#test').text(function(i,origText){
    return i+origText
})
回调函数的return是新的文本,函数体内必须要return;origText是原test的文本;i是当前元素的下标
同html、val
  • $('img').attr('src');--获得属性值;

修改多个属性值

$('img').attr({
    'src':url,
    'height':'120px'
})

也有回调函数,同text()


添加html元素

  • append() - 在被选元素的结尾插入内容<p>append</p>
$('p').append(html代码)
  • prepend() - 在被选元素的开头插入内容
$('#test').prepend(html代码)
  • after() - 在被选元素之后插入内容<p></p>after代码
$('p').after(html代码)
  • before()

删除html元素

$("#div1").remove(); //删除div1

$("#div1").empty();  //清空div1

$('p').remove('.hh') //删除class为hh的p

修改css

1. 

.class1{}
.class2{}

$('div').addClass('class1');

$('div').removeClass('class1');

$('div').toggleClass('class1')

2. css()

获取css值
alert($('div').css('width'))

修改css,方式一
$('div').css('width','120px')

修改css,方式二(传入的是个对象)
$('div').css({
    'height':'100px',
    'width':'120px'
})

其他的一些方法:hasClass()、removeProp()、removeClass()、offset()

 


尺寸:

width()/height(): content

innerWidth():content + padding

outerWidth() : content + padding + border

outerWidth(): content + padding + border + margin

当设置了box-sizing时:width()=width-padding-border


jq 对DOM遍历

1. 遍历祖先

span.parent(): 遍历他爸爸

span.parents('ul'): 遍历他所有祖先,并且祖先还得是ul

span.parentsUntil('div'): 遍历他所有祖先,直到这个祖先是div为止,并把div和span之间的祖先返回(不包括div)

2.遍历后代

$('div').children():返回div的所有儿子元素,孙子不返回

$('div').find('*') :返回div的所有后代(儿+孙)

3.兄弟

$('div').sliblins('span') div的所有兄弟元素,并且还得是span

.next() 下一个兄弟
.nextAll() 后面所有的兄弟
$('div').nextUntil('span') div和span之间所有的同为兄的的元素

prev()、prevAll()、prevUntil()同上面的next一摸一样,只不过变成了前... 

4.过滤

$('div p').find()  找整个html中第一个"div"下的第一个p   反之.last()

$('p').eq(1) 在整个html中找第2个p

$("p").filter(".url"); 整个html中返回所有class为url的p

$('p').not('.url') 整个html返回所有的class不为url的p

5.each()

  • $.each用来遍历数组和对象
1.遍历数组
var ary=[1,2,3,4,5]
$.each(ary,function(k,val){     //function中的参数是固定含义的,k是索引,val是对应值
    alert('索引值k'+k+' ary['+k+']='+val)
})

2.遍历对象
var p={name:'nmj',age:'18',sex:'woman'}
$.each(p,function(k,val){ //k是键值,val是value
    alert(k+'为:'+val) //输出: name为nmj
})
  • $('li').each用来遍历元素( this---->$(this))
遍历所有的li
$('li').each({
   alert($(this).text())
})

jq ajax

1. load()方法

 $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
    if(statusTxt=="success")
      alert("外部内容加载成功!");
    if(statusTxt=="error")
      alert("Error: "+xhr.status+": "+xhr.statusText);
  });

responseTxt - 调用成功时的结果内容
statusTXT - 调用的状态
xhr -  XMLHttpRequest 对象

2.get()  &&  post()

  • get 和 post的区别

get

 $.get("demo_test.php",function(data,status){ //固定参数
    alert("数据: " + data + "\n状态: " + status);
  });

 

post

var text={
    name:'nmj',
    age:'18'
}
$.post("/try/ajax/demo_test_post.php",text,  //text是向服务器发送的数据
    function(data,status){    //请求成功后的函数,data是从服务器上接收的数据,status是状态
        alert("数据: \n" + data + "\n状态: " + status);
    }
);

当jq中的$不能用的时候:

$.noConflict()
jQuery('button').click(); 
即将所有的$换成了jQuery

或者 
var jq=$.noConflict()
jq('button').click()

或者
jQuey(document).ready(function($){
    $('button').click()
})

 

 

 

 

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!