我正在寻找一种使用 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>
等等...
<div class="m4">Add this text margin = 4px</div>
<div class="p4">Add this text padding = 4px</div>
...
是否可以创建 jquery 代码来执行此操作? 也许这样做是为了填充。
想法:它也可以在 Bootstrap 中使用,比如添加自动填充、边距甚至 font-size
和 fs18
来添加 font-尺寸:18px
谢谢
最佳答案
这是一个选项。它也适用于填充。
传入“开始于”类和您要应用的 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');
<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>
关于jquery - 创建一个 jquery Margin 加法器类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35403745/