Javascript to change all absolutely positioned elements

Effectively what I need to do in JS is to move all absolutely positioned elements down x pixels. Do I need to iterate over each element and try to find out if it is absolutely positioned? Or is there a better way?

Thanks Mala

Update: . I use a bookmarklet to enter JS on any page, so I can’t change the markup or actual css files in any way. This bookmarklet should, among other things, move all absolutely positioned elements 155 pixels down.

+3
source share
4 answers

Something like this should do this:

function getStyle(el, prop) {
  var doc = el.ownerDocument, view = doc.defaultView;
  if (view && view.getComputedStyle) {
    return view.getComputedStyle(el, '')[prop];
  }
  return el.currentStyle[prop];
}
var all = document.getElementsByTagName('*'), i = all.length;
while (i--) {
  var topOffset = parseInt(all[i].style.top, 10);
  if (getStyle(all[i], 'position') === 'absolute') {
    all[i].style.top = isNaN(topOffset) ? '155px' : (topOffset + 155) + 'px';
  }
}
+2
source

You can mark all absolutely positioned elements with a specific class name and use getElementsByClassNamein most browsers . In addition, the only option is a loop.

+2
source

Phoenix un jQuery-ifed solution:

var nodes = document.getElementsByTagName("*");
node.foreach(function(n){ // can use foreach since this is FF only
    if(n.style.position=="absolute"){
        n.style.top += parseInt(n.style.top || 0, 10) +"px";
    }
}
+1
source

There is a CSS instruction position: fixed- which can do what you want ...

0
source

Source: https://habr.com/ru/post/1715313/


All Articles