开发者

Use jQuery set .css RIGHT if #foo + offset left is greater than page width

Ok, so I am trying to use jQuery to get the innerWidth() of an element #preview. I want to create a conditional that says IF x offset LEFT + #preview width is greater than page width, give it style right: z where z = #preview width + xOffset.

I apologize my code below is a mess and the syntax for .css ("right", (rightFloat + xOffset) + "px") (line 125) is off, but that's part of my problem.

<script>

    $(document).ready(function(){

    //append "gallery" class to all items with "popup" class
    imagePreview();
    $(".popup").addClass("gallery");
});    

//The overlay or pop-up effect
this.imagePreview = function() { /* CONFIG */

    xOffset = 40;
    yOffset = 40;

    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result
    /* END CONFIG */
    $("a.preview").click(function(e) {
        return f开发者_开发问答alse;
    });
    $("a.preview").hover(function(e) {
        this.t = this.title;
        this.title = "";
        var c = (this.t != "") ? "<br/>" + this.t : "";
        var rightFloat = e.pageX + ("#preview").innerWidth;
        $("body").append("<p id='preview'><img src='" + this.href + "' alt='Image preview' />" + c + "</p>");
        $("#preview").hide().css("top", (e.pageY - yOffset) + "px").css("left", (e.pageX + xOffset) + "px").fadeIn("2000");
        while ((left + 400) > window.innerWidth) {.css("right", (rightFloat + xOffset) + "px")
        }
    }, function() {
        this.title = this.t;
        $("#preview").remove();
    });
    $("a.preview").mousemove(function(e) {
        var top = e.pageY - yOffset;
        var left = e.pageX + xOffset;
        var rightFloat = e.pageX + ("#preview").innerWidth;
        //flips the image if it gets too close to the right side
        while ((left + 400) > window.innerWidth) {.css("right", +(rightFlaot + xOffset) + "px")
        }
        $("#preview").css("top", top + "px").css("left", left + "px");
    });
};


</script>


Try using http://api.jquery.com/offset/

if($('#preview').offset().right<0){
   var right = parseInt($(window).width()) - e.pageX + xOffset;
   $("#preview").css("top", top + "px").css("right", right + "px");
}else{
   var left = e.pageX + xOffset;
   $("#preview").css("top", top + "px").css("left", left + "px");
}

I made these fixes because I couldn't get your code to work in jsfiddle: var xOffset = 40; var yOffset = 40; $("a.preview").bind('mouseover',function(e){ var rightFloat = parseFloat(e.pageX)+$("#preview").innerWidth();
var ptop = parseFloat(e.pageY) - yOffset; var pleft = parseFloat(e.pageX) + xOffset; $("#preview").css({"top":ptop + "px","left":pleft + "px"}); });

There's the fixes for the top half but I have no idea what you're trying to do with the bottom part (with the while loop). Can you explain what functionality you want?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜