jQuery的css樣式設定和獲取
阿新 • • 發佈:2020-08-10
jQuery的css樣式設定和獲取
jquery中沒有style屬性,css通過.css()設定,不但可以獲取行內樣式的值,也可以獲取css設定的計算後樣式,相當於js中getcomputedStyle
- css()的引數可以是兩個,第二個是回撥函式
$("div").css("width",50); //不用加px $("div").css("width", function (index, item) { //設定不同的樣式 return (index + 1) * 50; }) console.log($("div").css("width")); //獲取計算後的樣式
2.css多個樣式的設定 css()的引數可以是個物件
$("div").css({ width: function (index, item) { return (index + 1) * 50; }, height: function (index, item) { return (index + 1) * 50; }, backgroundColor: function (index, item) { var color = "#"; for (var i = 0; i < 6; i++) { color += Math.floor(Math.random() * 16).toString(16); } return color; }, border: "1px solid #000000" });
3.css的樣式可以是個陣列 用來獲取第一個元素的指定樣式值,返回一個物件
console.log($("div").css(["width","height","backgroundColor"]));
4.新增和刪除className
$("div").addClass("div1"); $("div").addClass("div1 div2"); $("div").removeClass("div1"); $("div").removeClass("div1 div2");
5.設定css樣式,通過對className的新增刪除,達到元素樣式的控制(和vue的方法相同,實現響應式佈局)
var bool = false;
$("div").on("click", function () {
bool = !bool;
if (bool) $(this).removeClass("div1").addClass("div2");
else $(this).removeClass("div2").addClass("div1");
})
//簡單寫法
$("div").on("click",function(){
$(this).toggleClass("div2"); //點選刪除div2,再次點選新增div2,覆蓋之前的calssName
})
6.寬高的獲取和設定
$("div").width() //內容寬度width
//內容寬高的設定
$("div").width(100).height(100);
$("div").innerWidth() //width+padding 相當於js中的div.clientWidth
$("div").innerWidth(100); //width:80 有20px的padding
$("div").outerWidth() //width+padding+border 相當於js中的div.offsetWidth
$("div").outerWidth(100);//width:76 有20px的padding和4px的border
$("div").outerWidth(true) ///width+padding+border+margin
//只能獲取,不能設定
$(".div3").offset() //元素相對頁面左上角的位置 相當於js中的div.offsetleft/offsetTop
$(".div3").offset({left:500,top:500}); //元素位置的設定
console.log($(".div3").position()) //得到的是定位位置
//只能獲取,不能修改
console.log($(".div2").scrollTop());
console.log($(".div2").scrollTop(1000));
//獲取和設定滾動條位置