【问题标题】:read class and apply css with javascript or jquery读取类并使用 javascript 或 jquery 应用 css
【发布时间】:2014-07-07 09:31:00
【问题描述】:

我想用带有数字的短类名应用 css。

例如,

如果我使用类名mt-100,则表示margin-top:100px

如果我使用类名mr-200,则表示margin-right:200px

如果我使用类名mt-100 mr-200,则表示margin-top:100pxmargin-right:200px

如果我使用类名pt-100 mt-100 mr-200,则表示padding-top:100pxmargin-top:100pxmargin-right:200px

我尝试了,但没有成功。

我不想让 css 中的每个类都像这样 --> .mt-100{margin-top:100}

你能帮我做这个吗?

提前谢谢你。

让我在下面向您展示我的代码,


<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function classStartsWith(str) {
  return $('div').map( function(i,e) {
    var classes = e.className.split(' ');
    for (var i=0, j=classes.length; i < j; i++) {
      if (classes[i].substr(0, str.length) == str) return e;
    }
  }).get();
}
function classEndWith(str) {
  return $('div').map( function(i,e) {
    var classes = e.className.split(' ');
    for (var i=0, j=classes.length; i < j; i++) {
            if (classes[i].indexOf('mt-') || classes[i].indexOf('mb-') || classes  [i].indexOf('mr-') || classes[i].indexOf('ml-') || classes[i].indexOf('pt-') || classes[i].indexOf('pb-') || classes[i].indexOf('pr-') || classes[i].indexOf('pl-'))
    {
                    var ct = classes[i].split('-');
                    var cts = ct[1];
            }
      if (classes[i].substr(0, str.length) == str) return e,cts;
    }
  }).get();
}
$(document).ready(function(){
    $(classStartsWith('mt-')).each(function(){
        $(this).css('margin-top', classEndWith('mt-')+'px');
    });
    $(classStartsWith('mb-')).each(function(){
        $(this).css('margin-bottom', classEndWith('mb-')+'px');
    });
    $(classStartsWith('mr-')).each(function(){
        $(this).css('margin-right', classEndWith('mr-')+'px');
    });
    $(classStartsWith('ml-')).each(function(){
        $(this).css('margin-left', classEndWith('ml-')+'px');
    });

    $(classStartsWith('pt-')).each(function(){
        $(this).css('padding-top',  classEndWith('pt-')+'px');
    });
    $(classStartsWith('pb-')).each(function(){
        $(this).css('padding-bottom',  classEndWith('pb-')+'px');
    });
    $(classStartsWith('pr-')).each(function(){
        $(this).css('padding-right',  classEndWith('pr-')+'px');
    });
    $(classStartsWith('pl-')).each(function(){
        $(this).css('padding-left',  classEndWith('pl-')+'px');
    });
});
    </script>

</head>


<body>

<div class="mt-100 mb-200" style="width:300px;height:300px;border:1px solid red">
aaaa
</div>
<div class="pt-200 mb-200" style="width:300px;height:300px;border:1px solid red">
bbb
</div>
<div class="pr-300 ml-300 mt300" style="width:300px;height:300px;border:1px solid red">
ccc
</div>
<div class="pl-200 mt200" style="width:300px;height:300px;border:1px solid red">
ddd
</div>
</body>

【问题讨论】:

  • 为什么不直接使用css类呢?像 .mt-100 {margin-tope: 100px;}
  • 为什么不使用data属性?就像例如&lt;div data-width="200"&gt;...&lt;/div&gt;.
  • 这没有任何意义,这与为元素设置内联样式基本相同。这有什么需求,一定有更好的解决方案?
  • @Esa 什么对你没有意义? OP方式还是...?
  • 这可能对jsfiddle.net/satpalsingh/DecNq有帮助

标签: javascript jquery css class apply


【解决方案1】:

您现在处理它的方式对于此类任务来说开销太大。

我建议您了解有关在 HTML 标记上使用 data 属性的更多信息。这些属性允许您定义标签特定设置,您可以使用 jQuery 轻松读取这些设置并使其响应数据。

例子:

<div class="my-div-class" data-mt="100" data-mb="200">...</div>
<div class="my-div-class" data-pt="200" data-mb="200">...</div>

<script>
    $(function() {
        // Walk through each element with this class
        $('.my-div-class').each(function() {
            var thisDiv = $(this), // cache this element
                thisData = thisDiv.data(), // get all data attributes
                thisCSS = {}; // create the css array

            // Check which data is set and update the css accordingly
            if (thisData['mt']) {
                thisCSS['margin-top'] = thisData['mt'] + 'px';
            }
            if (thisData['mb']) {
                thisCSS['margin-bottom'] = thisData['mb'] + 'px';
            }
            if (thisData['pt']) {
                thisCSS['padding-top'] = thisData['pt'] + 'px';
            }
            if (thisData['pb']) {
                thisCSS['padding-bottom'] = thisData['pb'] + 'px';
            }

            // Add the css to this element
            thisDiv.css(thisCSS);

            // The following two lines show the data in each div for debugging. 
            // Remove these lines when you don't need this info anymore.        
            thisDiv.append('<div>CSS: ' + JSON.stringify(thisCSS) + '</div>');
            thisDiv.append('<div>DATA: ' + JSON.stringify(thisData) + '</div>');
        });
    });
</script>

Here is the JSFiddle.

here.data() 上的 jQuery 文档。

还可以查看data-attribute 文档here

【讨论】:

  • @user3811773 很高兴听到您对此感到满意 :-) 最后,请接受此答案。
  • 这个支持ie8吗?我测试了填充在 ie8 中不起作用。但是当我直接输入样式 attr 或 css 时,填充正在工作。
  • 尝试将以下内容添加到页面标题&lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;Here 你可以阅读更多关于它的作用。此外,使用&lt;!DOCTYPE html&gt; 确保您使用的是HTML5。试试这个。您使用的是哪个版本的 jQuery?在某些旧版本中存在 IE 错误。
  • 我忘了添加meta标签和doctype :(......我用的是1.8.2版本的jquery。我觉得最新版本的jquery不兼容ie8。我明天测试一下.谢谢~
猜你喜欢
  • 2013-03-07
  • 1970-01-01
  • 2013-12-23
  • 2021-03-14
  • 2013-01-24
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 2012-11-06
相关资源
最近更新 更多