2

我正在为我的数据标题值使用内联样式表。如何删除内联样式表并在类中定义它?由于该值来自 data-caption 属性,我不知道该怎么做。在下面提供我的代码:

http://jsfiddle.net/rajkumart08/8YK2n/

<div  class="cubeCell" data-text="Search" class="desktopContactImage cubeCell"
   data-caption="&lt;a style='padding-left: 40px; font-size: 18px; color: grey;' href='http://www.w3schools.com/' &gt;Create&lt;/a&gt; &lt;div&gt; &lt;a style='padding-left: 40px; font-size: 18px; color: grey;' &gt;View/Edit&lt;/a&gt; &lt;/div&gt; &lt;a style='padding-left: 40px; font-size: 18px; color: grey;' &gt;Labels&lt;/a&gt;"
   data-image="http://intra.defie.co/images/Desktop_icons_02.07.13/search.png"></div>

   <div class="iphoneContactImage" data-caption="&lt;a style='margin-left: 92px; font-size: 18px; color: grey;' href='http://www.w3schools.com/' &gt;Create&lt;/a&gt; &lt;div&gt; &lt;a style='margin-left: 92px; font-size: 18px; color: grey;' &gt;View/Edit&lt;/a&gt; &lt;/div&gt; &lt;a style='margin-left: 92px; font-size: 18px; color: grey;' &gt;Labels&lt;/a&gt;"
      data-image="http://intra.defie.co/images/Desktop_icons_02.07.13/demoImage.png">iphoneImage</div>
4

1 回答 1

0

一种解决方案是使用 Javascript 解析样式(此问题的第一个答案:Can jQuery get all CSS styles associated with an element?)并创建一个函数将它们转储到样式中。

然后,您可以动态地将这种样式添加到您的页面中(这个问题的第一个答案:如何在 JavaScript 中动态创建 CSS 类并应用?)。

编辑:

要访问data-caption属性,您可以使用$('.cubeCell').attr('data-caption')它将返回一个包含纯文本样式的字符串:

&lt;a style='padding-left: 40px; font-size: 18px; color: grey;' href='http://www.w3schools.com/' &gt;Create&lt;/a&gt; &lt;div&gt; &lt;a style='padding-left: 40px; font-size: 18px; color: grey;' &gt;View/Edit&lt;/a&gt; &lt;/div&gt; &lt;a style='padding-left: 40px; font-size: 18px; color: grey;' &gt;Labels&lt;/a&gt;

这与(替换 HTML 字符)相同:

<a style='padding-left: 40px; font-size: 18px; color: grey;' href='http://www.w3schools.com/' >Create</a>
<div>
   <a style='padding-left: 40px; font-size: 18px; color: grey;' >View/Edit</a>
</div>
<a style='padding-left: 40px; font-size: 18px; color: grey;' >Labels</a>

data-caption所以看起来你的属性不仅仅是样式。您应该使用正则表达式解析此字符串以仅检索styles. 然后,您将能够创建正确的样式并使用 Javascript 将它们添加到您的页面中。(如何使用正则表达式(javascript)获取样式=“我想要css代码”

编辑2:

假设您已经在字符串中有样式:

var mystyle = 'padding-left: 40px; font-size: 18px; color: grey;';

并且您想将其应用于已经具有内联样式的元素,例如您的示例。我将通过以下方式进行:

1)获取元素的HTML(无style属性)并将其分配给它所属的位置。例如:

原始代码

<div id="mylink">
    <a style='padding-left: 40px; font-size: 18px; color: grey;' href='http://www.w3schools.com/'>Create</a>
</div>

JS

$('#mylink').html('<a href='http://www.w3schools.com/'>Create</a>');

结果代码

<div id="mylink">
    <a href='http://www.w3schools.com/'>Create</a>
</div>

2)现在,添加您自己的类来处理样式:

$('#mylink a').addClass('mystyle');

3)最后,您只需要创建style元素并将其添加到您的页面:

var style = document.createElement('style');
var mystyle = 'padding-left: 40px; font-size: 18px; color: grey;';
style.type = 'text/css';
style.innerHTML = '.mystyle { ' + mystyle + ' }';
document.getElementsByTagName('head')[0].appendChild(style);

不要忘记尊重代码行的顺序,以便您的代码成功执行和应用样式。

于 2013-03-01T15:24:37.513 回答