如何将方法附加到对象以更改 CSS

How can I attach a method to an object to change CSS

本文关键字:对象 CSS 方法      更新时间:2023-09-26

我想制作一个方法,这样我就可以动态地更改元素的CSS,而无需document.getElementsByTagName("div")[0].style.borderColor = "red"长手方法,并实现类似jQuery库中发生的事情。但是,当我尝试将css方法附加到这样的元素时

var __shorthandCss = function(sel){
  var el = document.querySelectorAll(sel)[0];
  el.css = function(attrs){
       for (var attr in attrs){
         el.style[attr] = attrs[attr];
       }
  };
};

我收到错误:

Uncaught TypeError: Cannot read property 'css' of undefined

我在这里做错了什么?我是否以完全错误的方式这样做?

var __shorthandCss = function(sel) {
  var el = document.querySelectorAll(sel)[0];
  console.log(el);
  el.css = function(attrs) {
    for (var attr in attrs) {
      console.log(attr, attrs)
      el.style[attr] = attrs[attr];
    }
  };
};
var trig = function() {
  __shorthandCss("#a").css({
    "borderColor": "red"
  });
  console.log(a);
};
document.getElementById("b").addEventListener("click", trig);
div {
  border: 1px solid black;
  padding: 5px;
  width: 150px;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <button type="button" id="b">change border</button>
  <div id="a">test div</div>
</body>
</html>

你没有从函数返回 el

当你调用__shorthandCss()时,不会返回任何css()函数作为属性存在的,所以你需要返回你分配了css()的el。

var __shorthandCss = function(sel){
  var el = document.querySelectorAll(sel)[0];
  console.log(el);
  el.css = function(attrs){
       for (var attr in attrs){
         console.log(attr, attrs)
         el.style[attr] = attrs[attr];
       }
  };
  return el;
};

推荐

您可以使用document.querySelector(sel)而不是document.querySelectorAll(sel)[0]因为它执行相同的操作

工作演示:

var __shorthandCss = function(sel){
  
  var el = document.querySelector(sel);
  console.log(el);
  el.css = function(attrs){
    
       for (var attr in attrs){
         console.log(attr, attrs)
         el.style[attr] = attrs[attr];
       }
    
  };
  return el;
};
var trig = function(){
   __shorthandCss("#a").css({"borderColor": "red"});
   console.log(a);
};  
document.getElementById("b").addEventListener("click", trig);
  
  
div{
  border: 1px solid black;
  padding: 5px;
  width: 150px;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <button type="button" id="b">change border</button>
  <div id="a">test div</div>
</body>
</html>