admin管理员组

文章数量:1316833

I have a javascript bookmarklet I put together to make an arduous task a little more bearable. Essentially I am going through hundreds of pages of training material and making sure that all of it has been properly swapped from Helvetica to Arial. The bookmarklet code is below, but a quick breakdown is that it creates a mousemove event listener and a small, absolutely positioned div. On mousemove events, the div moves to the new mouse position (offset by 10px down and right), gets the element under the mouse with elementFromPoint and shows the font-family property for that element. oh and it changes it's background color based on whether Arial appears within the property.

var bodyEl=document.getElementsByTagName("body")[0];
var displayDiv=document.createElement("div");
displayDiv.style.position="absolute";
displayDiv.style.top="0px";
displayDiv.style.top="0px";
bodyEl.appendChild(displayDiv);


function getStyle(el,styleProp) {
  var camelize = function (str) {
    return str.replace(/\-(\w)/g, function(str, letter){
      return letter.toUpperCase();
    });
  };

  if (el.currentStyle) {
    return el.currentStyle[camelize(styleProp)];
  } else if (document.defaultView && document.defaultView.getComputedStyle) {
    return document.defaultView.getComputedStyle(el,null)
                               .getPropertyValue(styleProp);
  } else {
    return el.style[camelize(styleProp)]; 
  }
}
function getTheElement(x,y) {return document.elementFromPoint(x,y);}

fn_displayFont=function displayFont(e) {
    e = e || window.event;
    var divX=e.pageX+10;
    var divY=e.pageY+10;
    var font=getStyle(getTheElement(e.pageX,e.pageY),"font-family");
    if (font.toLowerCase().indexOf("arial") != -1) {
        displayDiv.style.backgroundColor = "green";
    } else {
        displayDiv.style.backgroundColor = "red";
    }
    displayDiv.style.top= divY.toString() + "px";
    displayDiv.style.left= divX.toString() + "px";
    displayDiv.style.fontFamily=font;
    displayDiv.innerHTML=font;
}

window.addEventListener('mousemove', fn_displayFont);
document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        window.removeEventListener('mousemove', fn_displayFont);
        bodyEl.removeChild(displayDiv);
    }
};

(for the record, I stole the style determining code from an answer here on SO, but I lost the tab not long after. Thanks, anonymous internet guy!) So this all works great - UNTIL I try to hover over a part of the page that is scrolled down from the top. The div sits at where it would be if I had the mouse on the very bottom of the screen while scrolled to the top of the page, and if I scroll down far enough firebug starts logging that e.pageX is undefined.

Any ideas?

I have a javascript bookmarklet I put together to make an arduous task a little more bearable. Essentially I am going through hundreds of pages of training material and making sure that all of it has been properly swapped from Helvetica to Arial. The bookmarklet code is below, but a quick breakdown is that it creates a mousemove event listener and a small, absolutely positioned div. On mousemove events, the div moves to the new mouse position (offset by 10px down and right), gets the element under the mouse with elementFromPoint and shows the font-family property for that element. oh and it changes it's background color based on whether Arial appears within the property.

var bodyEl=document.getElementsByTagName("body")[0];
var displayDiv=document.createElement("div");
displayDiv.style.position="absolute";
displayDiv.style.top="0px";
displayDiv.style.top="0px";
bodyEl.appendChild(displayDiv);


function getStyle(el,styleProp) {
  var camelize = function (str) {
    return str.replace(/\-(\w)/g, function(str, letter){
      return letter.toUpperCase();
    });
  };

  if (el.currentStyle) {
    return el.currentStyle[camelize(styleProp)];
  } else if (document.defaultView && document.defaultView.getComputedStyle) {
    return document.defaultView.getComputedStyle(el,null)
                               .getPropertyValue(styleProp);
  } else {
    return el.style[camelize(styleProp)]; 
  }
}
function getTheElement(x,y) {return document.elementFromPoint(x,y);}

fn_displayFont=function displayFont(e) {
    e = e || window.event;
    var divX=e.pageX+10;
    var divY=e.pageY+10;
    var font=getStyle(getTheElement(e.pageX,e.pageY),"font-family");
    if (font.toLowerCase().indexOf("arial") != -1) {
        displayDiv.style.backgroundColor = "green";
    } else {
        displayDiv.style.backgroundColor = "red";
    }
    displayDiv.style.top= divY.toString() + "px";
    displayDiv.style.left= divX.toString() + "px";
    displayDiv.style.fontFamily=font;
    displayDiv.innerHTML=font;
}

window.addEventListener('mousemove', fn_displayFont);
document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        window.removeEventListener('mousemove', fn_displayFont);
        bodyEl.removeChild(displayDiv);
    }
};

(for the record, I stole the style determining code from an answer here on SO, but I lost the tab not long after. Thanks, anonymous internet guy!) So this all works great - UNTIL I try to hover over a part of the page that is scrolled down from the top. The div sits at where it would be if I had the mouse on the very bottom of the screen while scrolled to the top of the page, and if I scroll down far enough firebug starts logging that e.pageX is undefined.

Any ideas?

Share Improve this question edited Nov 2, 2012 at 6:55 Chris O'Kelly asked Nov 2, 2012 at 5:19 Chris O'KellyChris O'Kelly 1,8932 gold badges18 silver badges36 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

Alrighty then, figured it out. I saw http://www.daniweb./web-development/javascript-dhtml-ajax/threads/276742/elementfrompoint-problems-when-window-has-been-scrolled- and thought it meant I had to minus the pageoffset straight away from the e.pageX/Y values, before I used it to calculate the div position or anything else, this just broke everything for me so I assumed it must have been unrelated - not so! From what I now understand the elementFromPoint method takes a point relative in the current view of the browser, which is to say, base on the top left corner of what can currently be seen, not the page as a whole. I fixed it by just taking the offset from the X and Y values when I was getting the element. The now-working code is below.

var bodyEl=document.getElementsByTagName("body")[0];
var displayDiv=document.createElement("div");
displayDiv.style.position="absolute";
displayDiv.style.top="0px";
displayDiv.style.top="0px";
bodyEl.appendChild(displayDiv);


function getStyle(el,styleProp) {
  var camelize = function (str) {
    return str.replace(/\-(\w)/g, function(str, letter){
      return letter.toUpperCase();
    });
  };

  if (el.currentStyle) {
    return el.currentStyle[camelize(styleProp)];
  } else if (document.defaultView && document.defaultView.getComputedStyle) {
    return document.defaultView.getComputedStyle(el,null)
                               .getPropertyValue(styleProp);
  } else {
    return el.style[camelize(styleProp)]; 
  }
}
function getTheElement(x,y) {return document.elementFromPoint(x,y);}

fn_displayFont=function displayFont(e) {
    e = e || window.event;
    var divX=e.pageX + 10;
    var divY=e.pageY + 10;
    var font=getStyle(getTheElement(e.pageX - window.pageXOffset,e.pageY - window.pageYOffset),"font-family");
    if (font.toLowerCase().indexOf("arial") != -1) {
        displayDiv.style.backgroundColor = "green";
    } else {
        displayDiv.style.backgroundColor = "red";
    }
    displayDiv.style.top= divY.toString() + "px";
    displayDiv.style.left= divX.toString() + "px";
    displayDiv.style.fontFamily=font;
    displayDiv.innerHTML=font;
}

document.addEventListener('mousemove', fn_displayFont);
document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        window.removeEventListener('mousemove', fn_displayFont);
        bodyEl.removeChild(displayDiv);
    }
};

Hmm instead of checking with the mouse, why not just check every leaf node? If any leaf node has a font-family of arial, then it should indicate that one of its ancestors has a font-family of Arial.

First you need to get jquery onto the page. Try this bookmarklet

Then run this code:

(function(){
    var arialNodes = $('div:not(:has(*))').filter(function(){
        return $(this).css('font-family').toLowerCase().indexOf("arial") != -1;
    });
})();

The arialNodes variable should contain every leaf node that has a font-family of 'Arial'. You can then use this to figure out which parent element has the declaration.

Or if you just want to see if a page is pliant or not, just check the length.

Updated

Updated to reflect ments below

(function() {
    var arialNodes = $('*:not(:has(*))', $('body')).filter(function() {
        return $(this).css('font-family').toLowerCase().indexOf("arial") === -1;
    });

    var offendingParents = [];
    arialNodes.each(function(){
        var highestOffendingParent = $(this).parentsUntil('body').filter(function(){
            return $(this).css('font-family').toLowerCase().indexOf("arial") === -1;
        }).last();
        if(offendingParents.indexOf(highestOffendingParent) === -1){
            offendingParents.push(highestOffendingParent);
        }
    });

})();

本文标签: javascriptelementFromPoint returns null after scrolling the pageStack Overflow