创建一个jquery Margin加法器类

Jaf*_*aei 7 html css jquery automation margin

我正在寻找一种方法来使用jquery添加任何数字的边距.它应该是这样的:

<div class="mr5">Add this text margin-right = 5px</div>
<div class="ml15">Add this text margin-left = 15px</div>
<div class="mt6">Add this text margin-top = 6px</div>
<div class="mb4">Add this text margin-bottom = 4px</div>
Run Code Online (Sandbox Code Playgroud)

等等 ...

<div class="m4">Add this text margin = 4px</div>
<div class="p4">Add this text padding = 4px</div>
...
Run Code Online (Sandbox Code Playgroud)

是否可以创建jquery代码来执行此操作?也许这样做是为了填充.

想法: 它可以在引导中使用太像添加自动填充,边缘或甚至font-sizefs18添加字体大小:18像素

谢谢

Ben*_*enG 6

这是一个选项.它也适用于填充.

传递'start with'类和要应用的css.

然后它将使用正则表达式来获取要应用的值并css应用它.

function addCss(startClass, css) {
  $('[class^="' + startClass + '"]').each(function() {
    var px, reg = new RegExp(startClass + "(\\d+)", 'g');
    if ((px = reg.exec(this.className)) != null) {
      $(this).css(css, px[1] + 'px');
    }
  });
}

addCss('mr', 'margin-right');
addCss('ml', 'margin-left');
addCss('mt', 'margin-top');
addCss('mb', 'margin-bottom');

//addCss('pl', 'padding-left');
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="mr5">Add this text margin-right = 5px</div>
<div class="ml15">Add this text margin-left = 15px</div>
<div class="mt6">Add this text margin-top = 6px</div>
<div class="mb4">Add this text margin-bottom = 4px</div>
<div class="mb40">Add this text margin-bottom = 4px</div>
<div class="mb4">Add this text margin-bottom = 4px</div>
<div class="mb400">Add this text margin-bottom = 4px</div>
<div class="mb4">Add this text margin-bottom = 4px</div>
Run Code Online (Sandbox Code Playgroud)