如何用jQuery中的变量进行计算? [英] How to do calculations with variables in jQuery?
问题描述
我正在创建一个程序,允许用户更改div的大多数CSS属性。我需要它居中,我通常这样做的方式是使用下面的CSS代码。
I am creating a program to allow a user to change most CSS properties of a div. I need it to be centred though, the way I usually do this is with the CSS code below.
div {
position: fixed;
background: black;
width: 100px;
height: 100px;
top: calc(50% - 50px);
right: calc(50% - 50px);
}
我需要将宽度和高度设为自己的变量然后做一个计算顶部和右边的属性,将它们除以2并从50%开始。
I need to make the width and height their own variables however and then do a calculation for the top and right properties which will divide them by 2 and take away from 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?
How can I go about achieving a centred div while using variables as the values for CSS properties?
推荐答案
如果你不需要支持糟糕的IE CSS变量是一个选项。
If you don't need to support crappy IE CSS variables are an option.
CSS
- 在样式表中选择一个范围。选择器在DOM上越高,它覆盖的越多。在Snippet中我选择了最高的:
:root
(即html
)。 - 声明CSS变量:
:root --half:50px
CSSVar必须以2个破折号为前缀。在Snippet中,我在:root
上声明了一个- half
,其值为50px
。 - 接下来,将CSSVar分配给相应的属性:
-
top:calc(50% - var( - half));
-
right:calc(50% - var( --half));
-
- Pick a scope in your stylesheet. The higher the selector is on the DOM, the more it'll cover. In the Snippet I chose the highest possible:
:root
(i.e.html
). - Declare CSS variable:
:root --half: 50px
CSSVar must be prefixed with 2 dashes. In the Snippet I have declared a--half
on:root
with the value of50px
. - Next, assign CSSVar to the appropriate properties:
top: calc(50% - var(--half));
right: calc(50% - var(--half));
JavaScript
- 详细信息在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;
}
<div id='shape1'></div>
<input id='input1' type='number' min='-150' max='150' value='50'>
这篇关于如何用jQuery中的变量进行计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!