简体   繁体   中英

Manipulate CSS of class that is to be added after DOM load

I have a news scroller which is created by appending li s from an array to a ul element. I am making it scroll via the following function:

$newsItem = $('.news-item');

function newsScroll() {
  $newsItem.eq(currentNewsItem).fadeIn(1000);
  setTimeout(function() {
    $newsItem.eq(currentNewsItem).addClass('move-left');
  }, 2000);
}

It adds .move-left class to li where .move-left has CSS rules:

.move-left {
  -webkit-transition: 5s;
  -moz-transition: 5s;
  -ms-transition: 5s;
  -o-transition: 5s;
  transition: 5s;
  left: -400px;
}

The problem is that all the news items are not the same length; some of them exceed the 400px. Thus moving them 400px left, doesn't scroll them out of the display of the scroller.

So I have used the following code to determine the width of the longest of these elements, but I am unsure how to affix this to the class .move-left , or how to alter a class that is not a part of the DOM.

var moveLeftAmt = Math.max.apply(null, $('ul#newsScroller li').map(function() {
  return $(this).outerWidth(true);
}).get());

Any suggestions?

probably you can do like this:

var moveLeftAmt = Math.max.apply(null, $('ul#newsScroller li').map(function() {
return $(this).outerWidth(true);
}).get());

So with above code you will get the highest width in moveLeftAmt and then apply it to the element as an inline css using the following code:

$newsItem.eq(currentNewsItem).css('left',moveLeftAmt);

OR

$newsItem.eq(currentNewsItem).attribute('style',"left:"+moveLeftAmt+"px;");  // Appended `px` after the variable.

Partially based on the suggestion of @HimanshuUpadhyay, I altered the style of the body tag via the attr function, including a CSS var like so:

$('body').attr('style',"--amtLeft:"+moveLeftAmt);

which I then referenced in the stylesheet:

.move-left {
  -webkit-transition: 5s;
  -moz-transition: 5s;
  -ms-transition: 5s;
  -o-transition: 5s;
  transition: 5s;
  left: var(--amtLeft) !important;
}

Works like a charm!

I should note that

var moveLeftAmt = Math.max.apply(null, $('ul#newsScroller li').map(function() {
  return $(this).outerWidth(true);
}).get());

simply returns a number, so to use it in this way I had to declare another variable that adds the "px" to the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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