Javascript删除元素样式

Javascript删除元素样式,javascript,css,Javascript,Css,可能重复: 我正在用js修改元素溢出,当我这样做时: document.body.style.overflow = 'hidden'; 该元素变为: <body style="overflow: hidden;"></body> 这没什么用。如何做到这一点?你可以这样做 document.body.setAttribute('style',''); 你可以这么做 document.body.setAttribute('style',''); 只需像这样清除sty

可能重复:

我正在用js修改元素溢出,当我这样做时:

document.body.style.overflow = 'hidden';
该元素变为:

<body style="overflow: hidden;"></body>
这没什么用。如何做到这一点?

你可以这样做

document.body.setAttribute('style','');
你可以这么做

document.body.setAttribute('style','');

只需像这样清除
style
属性:

document.body.setAttribute("style", "");

请记住,CSS可以来自许多部分(样式属性、外部样式表、HTML标记和javascript)

只需像这样清除
style
属性:

document.body.setAttribute("style", "");

请记住,CSS可以来自许多部分(样式属性、外部样式表、HTML标记和javascript)

假设您只是试图更改当前属性(即使只是简单地取消设置),这将导致问题。问题似乎在于空字符串不被视为CSS属性的合法值,因此不会添加到
style
属性中

在Chromium中,这可以解决,但只能显式地为属性声明一个新值,即使只使用
auto
关键字。考虑到这一点,一种方法如下:

var propStates = {
    // define the states, I'm only using two for a 'toggle'
    // approach, adjust to taste.
    'overflow': ['hidden', 'auto'],
    'display': ['block', 'auto']
}

function removeCSSProperty(el, prop) {
    if (!el || !prop) {
        return false;
    }
    else {
        // el can be either a node-reference *or* a string containing
        // the id of the element to adjust
        el = el.nodeType == 1 ? el : document.getElementById(el);
        var current = window.getComputedStyle(el, null)[prop];
        el.style[prop] = propStates[prop][0] == current ? propStates[prop][1] : propStates[prop][0];
    }
}

document.getElementById('adjust').onclick = function() {
    removeCSSProperty('test', 'overflow');
};​


这种方法要求浏览器理解
window.getComputedStyle()
函数,即假设您只是试图更改当前属性(即使只是简单地取消设置),这将导致问题。问题似乎在于空字符串不被视为CSS属性的合法值,因此不会添加到
style
属性中

在Chromium中,这可以解决,但只能显式地为属性声明一个新值,即使只使用
auto
关键字。考虑到这一点,一种方法如下:

var propStates = {
    // define the states, I'm only using two for a 'toggle'
    // approach, adjust to taste.
    'overflow': ['hidden', 'auto'],
    'display': ['block', 'auto']
}

function removeCSSProperty(el, prop) {
    if (!el || !prop) {
        return false;
    }
    else {
        // el can be either a node-reference *or* a string containing
        // the id of the element to adjust
        el = el.nodeType == 1 ? el : document.getElementById(el);
        var current = window.getComputedStyle(el, null)[prop];
        el.style[prop] = propStates[prop][0] == current ? propStates[prop][1] : propStates[prop][0];
    }
}

document.getElementById('adjust').onclick = function() {
    removeCSSProperty('test', 'overflow');
};​


这种方法要求浏览器理解
window.getComputedStyle()
函数,也就是说,这里的“可能”看起来像某种引导错误,因为它应该完全按照您的要求工作。这里的“可能”看起来像某种引导错误,因为这应该完全按照您的要求工作。OP只想删除
溢出
,而不是所有样式。OP只想删除
溢出
,而不是所有样式。。