繁体   English   中英

如何使用Jquery从外部html结构中获取css值?

[英]How to get the css value from outer html structure using Jquery?

嗨,我有以下HTML代码

   <div id="im" style="width:20px; color:red;" >12</div>

我需要得到这个html结构<div id="im" style="width:20px; color:red;" > <div id="im" style="width:20px; color:red;" >变量。 我怎么这样?

要获取div中的文本或内容,我们可以使用

$( "#im" ).html();

但我想得到htm结构,而不是内容。 请帮忙。

编辑

我知道我们可以使用$( "#im" ).prop('outerHTML');

从这个结果我怎么能得到width

我知道我们可以使用.css(“width”),但我需要从prop('outerHTML')得到它。

请帮忙 。

您可以从DOM元素对象的outerHTML属性中获取它。 在哪里可以使用索引从jQuery目标中获取DOM元素

$("#im")[0].outerHTML

更新1:要从属性获取宽度,请使用attr()方法获取属性值,使用String#match方法从字符串中使用正则表达式获取样式属性值。

 console.log( $('#im').attr('style').match(/width\\s?:([^;]+)/)[1] ) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="im" style="width:20px; color:red;">12</div> 


更新2:虽然您可以使用css()方法获取使用属性计算。

 console.log( $('#im').css('width') ) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="im" style="width:20px; color:red;">12</div> 


更新3:从字符串中获取它用jQuery包装并执行相同操作。

 console.log( $($('#im')[0].outerHTML).css('width') ) // or console.log( $($('#im')[0].outerHTML).attr('style').match(/width\\s?:([^;]+)/)[1] ) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="im" style="width:20px; color:red;">12</div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM