1. 程式人生 > >jQuery的屬性設定、CSS樣式設定和DOM的寬高位置設定

jQuery的屬性設定、CSS樣式設定和DOM的寬高位置設定

  • 屬性設定

  • 新增和獲取屬性

//新增屬性
$("div").attr("names","li");

//獲取屬性
$("div").attr("names");
  • 給多個物件新增同一屬性,但是不同的值

$("div").attr("names",function (index,value) {
        return "li"+index;
    })

//這樣就給每個div都根據他的index值設定了不同的names屬性
  • 給多個物件設定多個屬性,且有不同的值

$("div").attr({
        "names":function (index,value) {
            return "li"+index;
        },

        "toggle-data":function (index) {
            return "data"+index;
        }
    })


//總結:

$("選擇器").attr({
       "屬性1":function(index,value){
            return  值;
       },
       "屬性2":function(index,value){
            return  值;
       }
  })
  • CSS樣式設定

  • 新增獲取樣式

新增樣式:
$("div").css("backgroundColor","red");

獲取樣式:
$("div").css("backgroundColor")

還可以新增多個樣式:
$("div").css({
     "width":"100px",
     height:"100px"
})
  • 多個內容新增多個樣式

        $("div").css({
            "width":function (index) {
                return (index+1)*20+"px"
            },
            height:function (index) {
                return (index+1)*20+"px"
            },
            backgroundColor:function (index) {
                return "#"+(Math.floor(Math.random()*256*256*256)).toString(16)
            }
        })

       通過function的方法,給同一個樣式設定不同個的值
  • 直接新增樣式

        當新增多個樣式的時候可以使用空格分開
        $("div").addClass("div0 div2");
       可以移除其中的任意一個樣式
        $("div").removeClass("div2");

        這裡括號裡的樣式是樣式表中定義的樣式,不是標籤樣式
  • 切換樣式

        taggleClass()可以切換樣式,但是是樣式表裡的樣式

        $("div").addClass("div0").on("click",function (e) {
//            這裡的this是被點選的DOM物件
//            console.log(this);
            $(this).toggleClass("div1");       
        })

            括號裡面是true,切一次
            $(this).toggleClass("div1",true);
            括號裡面是false,不可切換
            $(this).toggleClass("div1",false);
  • DOM的寬高和位置設定

  • 簡單的設定和獲取

設定的,不用加單數,會自動加上
$("div").width(100);
$("div").height(100);
        

獲取寬度純數字,也不帶單位
console.log($("div").width())
console.log($("div").height())
  • 僅獲取的寬高

獲取寬和padding值
$("div").innerWidth();//width+padding

$("div").innerWidth(100);//其實可以設定,儘量不要設定這個寬高,因為內容加padding會影響佈局


outWidth是在上面的基礎上再多加一個border的值
$("div").outerWidth();//width+padding+border;


整個是在括號中填true,表示再多加上margin的值
$("div").outerWidth(true);//width+padding+border+margin

  • 僅獲取的滾動條的位置

        僅獲取,不可設定
        console.log($("div").offset().left);//{left,top};

        let {left,top}=$("div").offset();
        console.log(left,top);
        
        
        position相對於父元素定位的位置,offset是相對於頁面的位置
        console.log($(".div1").position());
        console.log($(".div1").offset());