2016-04-23 32 views
0

如果有任何應用,試圖找到一種方法來檢索元素inline css。但沒有內部/外部的CSS應用於元素。對於實施例 -如果存在任何元素(無內部或外部css),則獲取元素的內聯css

$('#get-inline').val($('#myh1').css('padding-top'));
#myh1{ 
 
    font-size: 20px; 
 
    padding-top: 10px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<h1 id="myh1" style="font-size:30px;">Heading 1</h1> 
 
<input type="text" id="get-inline" />

在上面的代碼中檢索其使用#myh1施加的CSS。但我需要它返回null""。否0NaN或其他。

如果我使用$('#myh1').attr('style');將返回所有內嵌的CSS。但我需要一種方式來獲得特定的 css我需要。

有沒有辦法實現我想要什麼?請幫助

尋找一個jQuery的解決方案。

回答

1

你可以使用這個腳本任何內部的CSS值:試試這個:

的jsfiddle:https://jsfiddle.net/hfud139c/

HTML:

<div id="myh1" style="padding-top:10px;height:10px;">Content</div> 

的Jquery:

$.fn.inlineStyle = function (prop) { 
     var styles = this.attr("style"), 
      value; 
     styles && styles.split(";").forEach(function (e) { 
      var style = e.split(":"); 
      if ($.trim(style[0]) === prop) { 
       value = style[1];   
      }      
     }); 
     return value; 
    }; 


    var width = $("#myh1").inlineStyle("padding-top"); 
+0

不是內部。只需要內聯。沒有外部或內部 –

+0

是的,我的意思是內聯css –

+0

可以創建一個jsfiddle plz?當我連接我的代碼時,它不工作。 –

0
<body> 
    <div id="target" style="color: red; background-color: yellow"> 
     Lorem ipsum <a href='#'>dolor</a> sit amet cosectetur... 
    </div> 
    <script> 
     function get_inline_stylesheet(source) 
     { 
      // clone node, so that future changes won't affect the original 
      // the (true) parameter is not needed, except if you judge it necessary 
      source = source.cloneNode(true) 
      // disable external stylesheet 
      source.setAttribute('style', 'all: reset;' + source.getAttribute('style')); 
      return source.style; 
     } 
     var target = document.querySelector('#target'); 
     var stylesheet = target.style; 
     console.log(stylesheet); 
     console.log(stylesheet.length); // 2 
     console.log(stylesheet[0]); // 'color'; 
     console.log(stylesheet[1]); // 'background-color'; 
    </script> 
</body> 
+0

試圖獲得某些CSS。不是所有的內聯CSS。 –

+0

你應該說,只有一些CSS'attribute'&這不是晚了,更正發佈 –

+0

猜你沒看過這部分 - 「如果我使用$(‘#爲myH1’)ATTR(‘風格’)。它會返回所有內聯的CSS,但我需要一種方法來獲得我需要的某些CSS。「 –

0

使用原生style屬性:

el.style['padding-top'] 

全部代碼在這裏:

$('#get-inline').val(document.getElementById('myh1').style['padding-top']); 
 
$('#get-inline2').val(document.getElementById('myh1').style['font-size']);
#myh1{ 
 
    font-size: 20px; 
 
    padding-top: 10px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<h1 id="myh1" style="font-size:30px;">Heading 1</h1> 
 
<input type="text" id="get-inline" /> 
 
<input type="text" id="get-inline2" />