我最近为 JavaScript 制作了一个自定义框架,但我的“.css()”函数不能作为对象表示法工作,这是我的代码的一部分:
const aps = function(selector) {
if (!(this instanceof aps)) {
return new aps(selector);
};
this.el = document.querySelectorAll(selector);
var about = {
Version: "0.3",
Author: "AppleProSchool, Adam Izgin",
Created: "Fall 2018, Tuesday 5, November",
Updated: "Tuesday 6, November",
}
};
aps.prototype.css = function(property, value) {
this.el.forEach(function(element) {
element.style[property] = value;
});
return this;
};
例如,如果我这样做:
(window.onload = function() {
aps('.test').css({ background: '#0f0' });//That does not return anything. Why?
});
但是当我这样做时:
(window.onload = function() {
aps('.test').css('background', '#0f0');//It works.
});
我确实有一个背景为红色的 div。
有什么想法吗?不管怎样,谢谢你。
最佳答案
您的函数需要两个参数:
aps.prototype.css = function(property, value) {
因此,当您向它发送一个参数(一个对象)时:
aps('.test').css({ background: '#0f0' })
property
参数包含 {background:'#0f0'}
,无法正确提取:
element.style[property]
并且该函数无法找到值
所需的信息,因此该值将是未定义
。
但是,当您发送两个参数时:
aps('.test').css('background', '#0f0')
它有效。
<小时/>如果您想使用对象语法,则需要更新函数以仅需要一个参数,并且该函数必须从该对象“解压”所需的数据。它看起来像这样:
aps.prototype.css = function(obj) {
this.el.forEach(function(element) {
// Use the first key name in the object and the first key value
element.style[Object.keys(obj)[0]] = Object.values(obj)[0];
});
return this;
};
关于JavaScript 自定义库 css 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53195588/