jQuery特殊属性操作

jQuery特殊属性操作

  1. val方法
    val方法用于设置和获取表单元素的值,例如input、textarea的值,返回值为 字符串类型

$("#name").val(“张三”);
//传入参数,设置value值
//如果这个jQuery对象不存在value属性,设置自定义属性value值
$("#name").val();
//不传参数,获取value值
//如果这个jQuery对象不存在value属性,返回为 空字符串
  1. html方法与text方法
    html方法相当于innerHTML,设置内容可以解析标签,获取内容含有标签
    text方法相当于innerText,设置内容不解析标签,获取内容不含标签
<div>我是div中的内容<h3>我是标题</h3></div>
//获取值
 console.log($("div").html());//我是div中的内容<h3>我是标题</h3>
console.log($("div").text());//我是div中的内容我是标题


<div></div>
//设置值
$("div").html("我是div中的内容<h3>我是标题</h3>")
//显示为  我是div中的内容 我是标题
$("div").text("我是div中的内容<h3>我是标题</h3>");
//显示为  我是div中的内容<h3>我是标题</h3>
  1. width和height方法
    传入参数设置值,返回为jQuery对象
    不传参数获取值,返回的值均为 数字类型,而用jQuery.css("width")获取,返回的为字符串类型
    //带参数表示设置宽度
    $(“img”).width(200);
    //不带参数获取宽度
    $(“img”).width();//200
//获取页面可视区的宽度和高度
//获取可视区宽度
$(window).width();
//获取可视区高度
$(window).height();

jQuery封装的其他获取宽度方法:

<style>
    div {
      width: 200px;
      height: 200px;
      background-color: red;
      padding: 10px;
      border: 10px solid #000;
      margin: 10px;
    }
  </style>
<div></div>

console.log($("div").width());//width  200
console.log($("div").innerWidth());//padding+width  220
console.log($("div").outerWidth());//padding+width+border  240 
console.log($("div").outerWidth(true));//padding+width+border+margin  260

height高度方法同width方法一样

  1. scrollTop与scrollLeft方法
    设置或者获取垂直/水平卷曲数,返回为 数字类型
//获取页面被卷曲的高度
$(window).scrollTop();
//获取页面被卷曲的宽度
$(window).scrollLeft();
  1. offset方法和position方法
    offset方法获取元素距离document的位置,返回为对象{left: 200, top: 200}
    position方法获取的是元素距离有定位的父元素的位置,返回为对象{left: 100, top: 100}
<style>
    * {
      margin: 0;
      padding: 0;
    }    
    .father {
      width: 400px;
      height: 400px;
      background-color: pink;
      position: relative;
      margin: 100px;
    }    
    .son {
      width: 200px;
      height: 200px;
      background-color: red;
      position: absolute;
      top: 100px;
      left: 100px;
    }
  </style>
<div class="father">
  <div class="son"></div>
</div>
 //获取元素的相对于document的位置
    console.log($(".son").offset());//{left: 200, top: 200}
    //获取元素相对于有定位的父元素的位置
    console.log($(".son").position());//{left: 100, top: 100}

猜你喜欢

转载自blog.csdn.net/qq_39369835/article/details/87655637