我想创建一个方法,这样我就可以动态更改元素的 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>
关于javascript - 如何将方法附加到对象以更改 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27649508/