Use jQuery to write width and height attributes to image tags
Hey folks, I have a page that has a long list of images. These images do not include either the width or height attributes. Unfortunately I don't have the ability to change how the images are coded in the HTML.
The issue is, I am linking to various parts of the page using anchors from other pages. When the page loads it jumps down to that anc开发者_开发百科hor. However, because the browser is not able to correctly determine the height of the images the anchor jumps down further and further as the images start filling in.
So, I was thinking, can jQuery determine the height of the images and append the width and height of the images on all image tags in a specific div? Or, is there a more elegant solution to this issue? Let me know your thoughts!
Nothing client side can know what the dimensions of the images are until the images have loaded — by which time the browser will have sized the img element itself.
jQuery can write width/height attributes to image tags, but it requires the browser to know their widths and heights - and to know these, the browser must have already loaded enough of each image to get these stats - so not very useful in your case. As you are incapable of changing the HTML or bending the time-space continuum to your will, there is no solution I know of for your question.
But wait, there's hope! If you want to scroll to the anchor after the document has loaded, you will need a scrollTo function (see http://plugins.jquery.com/project/ScrollTo). You MUST use an onload handler to ensure all images are loaded:
$(window).load(function () {
// scroll
});
I dont really understand what you mean by "the anchor jumps down further and further as the images start filling in" But from what i understand you can show a specific part of the pag by including #elementId at the end of you hyperlink. Correct me if i am wrong so i can edit my answer.
Follow-up-1:
Any commands in $(document).ready(...some code..)
only fire once the page has loaded.
Follow-up-2:
$(document).ready(function(){
var id = window.location.pathname.split("#");
$('html,body').animate({scrollTop: $("#"+id).offset().top}, 100);
});
精彩评论