简体   繁体   English

jQuery-动态更改CSS类的值

[英]jQuery - change value of css class dynamically

I have an image slider written in jQuery. 我有一个用jQuery写的图像滑块。 I need the images to be in groups of two (like a magazine) so i have classes .pageLeft and .pageRight that apply a left- or right-margin equal to the width of the container minus the width of a page img (.page class). 我需要将图像分成两个组(例如杂志),所以我有类.pageLeft和.pageRight,它们应用等于容器宽度减去页面img(.page类)。 I want to be able to fullscreen this slider and dynamically calculate and change the width of the .page and the margin value of the .pageLeft/.pageRight classes. 我希望能够全屏显示此滑块,并动态计算和更改.page的宽度以及.pageLeft / .pageRight类的边距值。 Is there any way to do this, or am I going about this all wrong? 有什么办法可以做到这一点,还是我做错了一切?

The best way I could think to do this would be to write the classes to the DOM directly, but then I would have to empty and add every time. 我想做到这一点的最佳方法是将类直接写入DOM,但是随后我将不得不清空并每次添加一次。

Here is an example of what I'm trying to say 这是我想说的一个例子

nPageWidth = 768;
nPageWidthPlusMargin = ($('#container').width() / 2);
nPageMargin = nPageWidthPlusMargin - nPageWidth;

and then use that value to change margin-left = nPageMargin for the class in the css. 然后使用该值更改css中类的margin-left = nPageMargin。

Sorry if this is a confusing question. 抱歉,这是一个令人困惑的问题。 Thanks for your time. 谢谢你的时间。

EDIT: The main reason I'm trying to do it this way is to maintain the aspect ratio of the images by setting the width of the image to be 3:4 the height of the image which is set to 100% of the container. 编辑:我试图这样做的主要原因是通过将图像的宽度设置为容器的100%的图像的高度为3:4来保持图像的长宽比。

I think you should use percentages for your margins instead of pixel values. 我认为您应该使用百分比而不是像素值。

$("#container .pageLeft").css("margin-right", "5%");
$("#container .pageRight").css("margin-left", "5%");

EDIT Then you won't have to compute margins again and again. 编辑然后,您将不必一次又一次地计算边距。

EDIT With CSS only: 仅使用CSS 编辑

#container .pageLeft {
  margin-right: 5%;
}
#container .pageRight {
  margin-left: 5%;
}

Is the purpose of the calculated margins to center the pages? 计算页边距的目的是使页面居中吗? In that case you could wrap the two pages in a wrapper, give that wrapper an explicit width, and set the left and right margins of the wrapper to auto . 在这种情况下,您可以将两个页面包装在一个包装器中,为该包装器指定一个明确的宽度,然后将包装器的左右边距设置为auto

Then you don't need to worry about calculating the margins. 然后,您无需担心计算边距。 Just make sure the wrapper has the correct width. 只要确保包装纸的宽度正确即可。 This width could, depending on your design, even be set as a percentage of the container. 根据您的设计,该宽度甚至可以设置为容器的百分比。 The same goes for the wrapped pages, they could have width: 50% . 包装的页面也是如此,它们的width: 50%可以是width: 50% This way you don't even need Javascript :) 这样,您甚至不需要Javascript :)

Fiddle: http://jsfiddle.net/F4ktm/ 小提琴: http : //jsfiddle.net/F4ktm/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM