jQuery之css操作

超实用的jQuery之css操作

童鞋们好,今天我给大家简单地说一下JQuery之CSS样式操作,希望能对大家有所帮助。

css操作主要有三种

1.css主要操作

2.位置操作

3.属性操作

1.css主要操作

HTML代码

  <div>金城武</div>
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>

css代码

   body{
        margin: 0;
        padding: 0;
    }
    div{
        width: 100px;
        height: 100px;
        background: red;
        margin-bottom: 10px;
        text-align: center;
        line-height: 100px;
    }
    span{
        display: block;
        width: 100px;
        height: 100px;
        background: yellow;
        margin-bottom: 5px;
        text-align: center;
        line-height: 100px;
        }

jQuery代码

     //css后面括号里一个值代表的是取得属性的值
     console.log($("div").css("background"));
     //两个值的时候是设置属性值
     $("div").css("background","red");
     //三个属性值的时候是 1:属性名
     //2:此函数返回要设置的属性值。接受两个参数,index为元素在对象集合中的索引位置,value是原先的属性值。
     $("span").click(function() {
        $(this).css({
            width: function(index, value) {
                return parseFloat(value) * 1.2;
            },
            height: function(index, value) {
                return parseFloat(value) * 1.2;
            }
        });
    });

代码运行效果

2.位置操作

HTML代码

     <div id="box"></div>
     <div id="box1">
         <div  id="box2"></div>
     </div>

css代码

    body{
        margin: 0;
        padding: 0;
    }
    #box{
        width: 100px;
        height: 100px;
        background: blue;
    }
    #box1{
        width: 200px;
        height: 200px;
        background: red;
        position: relative;
    }
    #box2{
        width: 100px;
        height: 100px;
        background: yellow;
        position: absolute;
        top: 50px;
        left: 50px;
    }

JQuery代码

    //获取匹配元素在当前视口的相对偏移。
    //返回的对象包含两个整型属性:top 和 left,以像素计。此方法只对可见元素有效。
       console.log($("#box").offset());
       $("#box").offset({top:20,left:20});

    //获取匹配元素相对父元素的偏移。
      返回的对象包含两个整型属性:top 和 left。为精确计算结果,请在补白、边框和填充属性上使用像素单位。此方法只对可见元素有效。
       console.log($("#box2").position());

    //获取匹配元素相对滚动条顶部的偏移。
    //获取匹配元素相对滚动条左侧的偏移。
    //此方法对可见和隐藏元素均有效。
     console.log($(window).scrollTop());
     console.log($(window).scrollLeft());

代码运行效果

3.属性操作

HTML代码

     <div id="box"></div>

JQuery代码

    //取得匹配元素当前计算的高度值(px)。
      $("#box").height();
    //设置元素的高
      $("p").height(60);
     //取得匹配元素当前计算的宽度值(px)。
      $("#box").width();
    //设置元素的宽
      $("p").width(60);

    //innerHeight:获取第一个匹配元素内部区域高度(包括补白、不包括边框)。
      此方法对可见和隐藏元素均有效。
       console.log($("#box").innerHeight());
    //innerWidth:获取第一个匹配元素内部区域宽度(包括补白、不包括边框)。
      此方法对可见和隐藏元素均有效。
       console.log($("#box").innerWidth());

     //outerHeight:获取第一个匹配元素外部高度。
      此方法对可见和隐藏元素均有效。
       console.log($("#box").innerHeight());
    //outerWidth:获取第一个匹配元素外部宽度。
      此方法对可见和隐藏元素均有效。
       console.log($("#box").innerWidth());

相信大家已经都简单地了解了,希望对大家有所帮助。

posted on 2017-05-13 12:17  web小爬虫  阅读(357)  评论(2编辑  收藏  举报

导航