jquery - 创建一个 jquery Margin 加法器类

标签 jquery html css 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>

等等...

<div class="m4">Add this text margin = 4px</div>
<div class="p4">Add this text padding = 4px</div>
...

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

想法:它也可以在 Bootstrap 中使用,比如添加自动填充、边距甚至 font-sizefs18 来添加 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/

相关文章:

event-handling - 使用 .on() 附加到文档时无法删除特定事件处理程序

javascript - 删除行后重新排序表编号顺序

javascript - JavaScript 与 Flash 之间的通信

html - 响应式文本框布局

javascript - jQuery 加载的异步和就绪函数不起作用

jquery - Slick JS,unslick() 删除问题

jquery - 检测具有固定位置的 div 何时跨过另一个元素

html - CSS 将菜单对齐到 div 的右侧

javascript - 背景图像更改按钮在 Firefox 中的默认样式

javascript - 在小间隔内通过 javascript 更新 css 时卡住轨道动画