如何用jQuery中的变量进行计算?

我正在创建一个程序,允许用户更改div的大多数CSS属性。 我需要它居中,我通常这样做的方式是使用下面的CSS代码。

div { position: fixed; background: black; width: 100px; height: 100px; top: calc(50% - 50px); right: calc(50% - 50px); } 

我需要将宽度和高度作为自己的变量,然后对顶部和右侧属性进行计算,将它们除以2并从50%中取出。

 var width = 100; var height = 100; var top = (height / 2); var right = (width / 2); $('div') .css('position','fixed') .css('background','black') .css('width',width + 'px') .css('height',height + 'px') .css('top','calc(50% - ' + top + 'px)') .css('right','calc(50% - ' + right + 'px)'); 

在将变量用作CSS属性的值时,如何实现居中的div?

如果你不需要支持糟糕的IE CSS变量是一个选项。

CSS

  1. 在样式表中选择一个范围。 选择器在DOM上越高,它覆盖的越多。 在Snippet中我选择了最高的:root (即html )。
  2. 声明CSS变量:: :root --half: 50px –half :root --half: 50px CSSVar必须以2个破折号为前缀。 在Snippet中,我声明了一个--half on :root ,其值为50px
  3. 接下来,将CSSVar分配给适当的属性:
    • top: calc(50% - var(--half));
    • right: calc(50% - var(--half));

JavaScript的

  1. 详细信息在Snippet中进行了评论。

SNIPPET

 // Reference the input var A = document.getElementById('input1'); // On input event on input#A call setHalf() function A.addEventListener('input', setHalf, false); /* setHalf() accesses the CSS by the CSSDeclaration || interface. */ function setHalf(e) { // Reference the div var X = document.getElementById('shape1'); /* Get div#shape1 computedStyle in order to || access it's ruleset declarations. */ var Y = window.getComputedStyle(X); // Get the value of the CSSVar --half var Z = Y.getPropertyValue('--half'); // Set --half value to the value of input#A X.style.setProperty('--half', this.value + 'px'); } 
 :root { --half: 50px; } #shape1 { position: fixed; background: black; width: 100px; height: 100px; top: calc(50% - var(--half)); right: calc(50% - var(--half)); border: 1px solid black; } 
 

所以事实certificate我无法使用“top”或“right”这两个词作为变量名。

这是最终工作的代码。

 var width = 100; var height = 100; var test1 = width / 2; var test2 = height / 2; $('div') .css('position','fixed') .css('background','black') .css('width',width + 'px') .css('height',height + 'px') .css({'top':'calc(50% - ' + test1 + 'px)'}) .css({'right':'calc(50% - ' + test2 + 'px)'});