簡體   English   中英

覆蓋 !important 風格

[英]Overriding !important style

標題幾乎總結了它。

外部樣式表具有以下代碼:

td.EvenRow a {
  display: none !important;
}

我試過使用:

element.style.display = "inline";

element.style.display = "inline !important";

但兩者都不起作用。 是否可以使用 javascript 覆蓋 !important 樣式。

這是一個greasemonkey 擴展,如果這有區別的話。

您可以使用幾個簡單的單線來執行此操作。

  1. 在元素上設置“樣式”屬性

    element.setAttribute('style', 'display:inline !important');

或者...

  1. 修改style對象的cssText屬性:

    element.style.cssText = 'display:inline !important';

要么會做這項工作。

===

我編寫了一個名為“important”的 jQuery 插件來操作元素中的!important規則,: http : //github.com/premasagar/important

===

編輯:正如評論中所分享的,標准 CSSOM 接口(用於與 CSS 交互的 JavaScript 的 API)提供了setProperty方法:

element.style.setProperty(propertyName, value, priority);

例如:

document.body.style.setProperty('background-color', 'red', 'important');

element.style有一個setProperty方法,可以將優先級作為第三個參數:

element.style.setProperty("display", "inline", "important")

在舊 IE 中不起作用,但在當前瀏覽器中應該沒問題

我相信唯一的方法是將樣式添加為帶有 '!important' 后綴的新 CSS 聲明。 最簡單的方法是在文檔的頭部附加一個新的 <style> 元素:

function addNewStyle(newStyle) {
    var styleElement = document.getElementById('styles_js');
    if (!styleElement) {
        styleElement = document.createElement('style');
        styleElement.type = 'text/css';
        styleElement.id = 'styles_js';
        document.getElementsByTagName('head')[0].appendChild(styleElement);
    }
    styleElement.appendChild(document.createTextNode(newStyle));
}

addNewStyle('td.EvenRow a {display:inline !important;}')

使用上述方法添加的規則(如果您使用 !important 后綴)將覆蓋其他先前設置的樣式。 如果您不使用后綴,請確保將“特殊性”等概念考慮在內。

您可以使用:

element.style.setProperty("display", "inline", "important");

https://developer.mozilla.org/zh-CN/docs/Web/API/CSSStyleDeclaration/setProperty

以@Premasagar 的出色回答為基礎; 如果您不想刪除所有其他內聯樣式,請使用此

//accepts the hyphenated versions (i.e. not 'cssFloat')
addStyle(element, property, value, important) {
    //remove previously defined property
    if (element.style.setProperty)
        element.style.setProperty(property, '');
    else
        element.style.setAttribute(property, '');

    //insert the new style with all the old rules
    element.setAttribute('style', element.style.cssText +
        property + ':' + value + ((important) ? ' !important' : '') + ';');
}

不能使用removeProperty()因為它不會刪除 Chrome 中的!important規則。
不能使用element.style[property] = ''因為它在 FireFox 中只接受駝峰式大小寫。

我剛剛發現的更好的方法:嘗試比使用選擇器的頁面CSS更具體。 我今天只需要這樣做,它就像一個魅力! W3C網站上的更多信息: http : //www.w3.org/TR/CSS2/cascade.html#specificity

如果要在 DOM 元素樣式屬性中更新/添加單個樣式,可以使用此功能:

function setCssTextStyle(el, style, value) {
  var result = el.style.cssText.match(new RegExp("(?:[;\\s]|^)(" +
      style.replace("-", "\\-") + "\\s*:(.*?)(;|$))")),
    idx;
  if (result) {
    idx = result.index + result[0].indexOf(result[1]);
    el.style.cssText = el.style.cssText.substring(0, idx) +
      style + ": " + value + ";" +
      el.style.cssText.substring(idx + result[1].length);
  } else {
    el.style.cssText += " " + style + ": " + value + ";";
  }
}

style.cssText支持所有主流瀏覽器

用例示例:

var elem = document.getElementById("elementId");
setCssTextStyle(elem, "margin-top", "10px !important");

這是演示的鏈接

如果您所做的只是向頁面添加 css,那么我建議您使用 Stylish 插件,並編寫用戶樣式而不是用戶腳本,因為用戶樣式更有效和更合適。

請參閱此頁面,了解有關如何創建用戶樣式的信息

https://developer.mozilla.org/en-US/docs/Web/CSS/initial

在 css3 中使用初始屬性

 <p style="color:red!important"> 
    this text is red 
       <em style="color:initial"> 
          this text is in the initial color (e.g. black)
       </em>
    this is red again
 </p>

https://jsfiddle.net/xk6Ut/256/

在 JavaScript 中覆蓋 CSS 類的一種選擇是使用樣式元素的 ID,以便我們可以更新 CSS 類

function writeStyles(styleName, cssText) {
    var styleElement = document.getElementById(styleName);
    if (styleElement) document.getElementsByTagName('head')[0].removeChild(
        styleElement);
    styleElement = document.createElement('style');
    styleElement.type = 'text/css';
    styleElement.id = styleName;
    styleElement.innerHTML = cssText;
    document.getElementsByTagName('head')[0].appendChild(styleElement);
}

..

   var cssText = '.testDIV{ height:' + height + 'px !important; }';
    writeStyles('styles_js', cssText)

如果你通過java腳本注入一個類(例如:'show'),而不是注入樣式,它就會起作用。 但在這里你需要像下面這樣的 css。 添加的 class css 規則應低於您的原始規則。

td.EvenRow a{
  display: none !important;
}

td.EvenRow a.show{
  display: block !important;
}

我們還有另一種可能從 CSS 中刪除屬性值。

就像在js中使用replace方法一樣。 但是您必須確切地知道樣式的 ID,或者您可以編寫一個 for 循環來檢測它(計算頁面上的樣式,然后檢查這些“包含”或“匹配”中的任何一個是否為!important值。&您也可以計算 - 有多少包含它們,或者只是簡單地編寫一個全局 [regexp: /str/gi] 替換方法)

我的很簡單,但是我附上了一個jsBin,例如:

https://jsbin.com/geqodeg/edit?html,css,js,output

首先,我在 CSS 中為 Yellow !important設置了正文背景,然后我用 JS 覆蓋了 darkPink。

下面是一段代碼,用於使用 jquery 設置樣式屬性的重要參數。

$.fn.setFixedStyle = function(styles){
    var s = $(this).attr("style");
    s = "{"+s.replace(/;/g,",").replace(/'|"/g,"");
    s = s.substring(0,s.length-1)+"}";
    s = s.replace(/,/g,"\",\"").replace(/{/g,"{\"").replace(/}/g,"\"}").replace(/:/g,"\":\"");
    var stOb = JSON.parse(s),st;
    if(!styles){
     $.each(stOb,function(k,v){
      stOb[k] +=" !important";
     });
    }
    else{
     $.each(styles,function(k,v){
      if(v.length>0){
        stOb[k] = v+" !important";
      }else{
        stOb[k] += " !important";  
      }
     });
    }
    var ns = JSON.stringify(stOb);
    $(this).attr("style",ns.replace(/"|{|}/g,"").replace(/,/g,";"));
};

用法非常簡單。只需傳遞一個包含您要設置為重要的所有屬性的對象。

$("#i1").setFixedStyle({"width":"50px","height":""});

還有兩個附加選項。

1. 將重要參數添加到已經存在的樣式屬性中,傳遞空字符串。

2.為所有存在的屬性添加重要參數,不要傳遞任何東西。 它會將所有屬性設置為重要。

這是它的現場直播。 http://codepen.io/agaase/pen/nkvjr

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM