jquery中position定位选项

官方参考http://jqueryui.com/position/

.position()


.position( options )Returns: jQueryversion added: 1.8

Description: Position an element relative to another.

  • .position( options )
    • options
      Type:  Object
      • my (default:  "center")
        Type:  String
        Defines which position  on the element being positioned to align with the target element: "horizontal vertical" alignment. A single value such as  "right" will be normalized to  "right center""top" will be normalized to  "center top" (following CSS convention). Acceptable horizontal values:  "left", "center""right". Acceptable vertical values:  "top""center""bottom". Example:  "left top" or "center center". Each dimension can also contain offsets, in pixels or percent, e.g.,  "right+10 top-25%". Perecentage offsets are relative to the element being positioned.
      • at (default:  "center")
        Type:  String
        Defines which position  on the target element to align the positioned element against: "horizontal vertical" alignment. See the  my option for full details on possible values. Perecentage offsets are relative to the target element.
      • of (default:  null)
        Type:  Selector or  Element or  jQuery or  Event
        Which element to position against. If you provide a selector or jQuery object, the first matching element will be used. If you provide an event object, the  pageX and  pageY properties will be used. Example:  "#top-menu"
      • collision (default:  "flip")
        Type:  String

        When the positioned element overflows the window in some direction, move it to an alternative position. Similar to my and at, this accepts a single value or a pair for horizontal/vertical, e.g., "flip""fit","fit flip""fit none".

        • "flip": Flips the element to the opposite side of the target and the collision detection is run again to see if it will fit. Whichever side allows more of the element to be visible will be used.
        • "fit": Shift the element away from the edge of the window.
        • "flipfit": First applies the flip logic, placing the element on whichever side allows more of the element to be visible. Then the fit logic is applied to ensure as much of the element is visible as possible.
        • "none": Does not apply any collision detection.
      • using (default:  null)
        Type:  Function()
        When specified, the actual property setting is delegated to this callback. Receives two parameters: The first is a hash of  top and  left values for the position that should be set and can be forwarded to .position() or  .animate().

        The second provides feedback about the position and dimensions of both elements, as well as calculations to their relative position. Both target and element have these properties: elementlefttopwidth,height. In addition, there's horizontalvertical and important, giving you twelve potential directions like { horizontal: "center", vertical: "left", important: "horizontal" }.

      • within (default:  window)
        Type:  Selector or  Element or  jQuery
        Element to position within, affecting collision detection. If you provide a selector or jQuery object, the first matching element will be used.

The jQuery UI .position() method allows you to position an element relative to the window, document, another element, or the cursor/mouse, without worrying about offset parents.

Note: jQuery UI does not support positioning hidden elements.

This is a standalone jQuery plugin and has no dependencies on other jQuery UI components.

This plugin extends jQuery's built-in .position() method. If jQuery UI is not loaded, calling the .position() method may not fail directly, as the method still exists. However, the expected behavior will not occur.

Example:

A simple jQuery UI Position example.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<!doctype html>
< html lang = "en" >
< head >
     < meta charset = "utf-8" >
     < title >position demo</ title >
     < link rel = "stylesheet" href = "http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" >
     < style >
     .positionDiv {
         position: absolute;
         width: 75px;
         height: 75px;
         background: green;
     }
     </ style >
     < script src = "http://code.jquery.com/jquery-1.8.2.js" ></ script >
     < script src = "http://code.jquery.com/ui/1.9.0/jquery-ui.js" ></ script >
</ head >
< body >
 
< div id = "targetElement" >
     < div class = "positionDiv" id = "position1" ></ div >
     < div class = "positionDiv" id = "position2" ></ div >
     < div class = "positionDiv" id = "position3" ></ div >
     < div class = "positionDiv" id = "position4" ></ div >
</ div >
 
< script >
$( "#position1" ).position({
     my: "center",
     at: "center",
     of: "#targetElement"
});
 
$( "#position2" ).position({
     my: "left top",
     at: "left top",
     of: "#targetElement"
});
 
$( "#position3" ).position({
     my: "right center",
     at: "right bottom",
     of: "#targetElement"
});
 
$( document ).mousemove(function( event ) {
     $( "#position4" ).position({
         my: "left+3 bottom-3",
         of: event,
         collision: "fit"
     });
});
</ script >
 
</ body >
</ html >
Demo:

===================================================================================================

图解

First things first

We'll be using jQuery and jQuery UI here, so we are assuming you are loading the jQuery and jQuery UI libraries on your site.

<head>
...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
...
<script type="text/javascript">
$(function() {
     // do stuff, yay!
});
</script>
</head>

The Basics

One of the sweet things about jQuery and jQuery UI is the almost sentence-like syntax of writing it. One-word function names and parameters that really drive home what is going on. Here is a basic example.

$("#move-me").position({
	"my": "right top",
	"at": "left bottom",
	"of": $("#thing")
});

Maybe a little graphic will help:

The coolest part here is that there are no prerequisites for this to work. The element being positioned doesn't need any special CSS positioning value (or to be a child element), the element being positioned against doesn't need any special CSS positioning value (or anything else).

All Options

Here is the full set. Only just a few more options.

$('.positionable').position({
	"my": "right top"       //  Horizontal then vertical, missing values default to center
	"at": "left bottom"     //  Horizontal then vertical, missing values default to center
	"of": $('#parent'),     //  Element to position against 
	"offset": "20 30"       //  Pixel values for offset, Horizontal then vertical, negative values OK
	"collision": "fit flip" //  What to do in case of 
	"bgiframe": true        //  Uses the bgiframe plugin if it is loaded and this is true
});

We covered "my", "of", and "at" in the basics, but the full set of parameters include setting an offset, using the bgiframe plugin (fixes some IE z-index issues), and collision detection, which I'll cover later.

Magic Zoom!

I thought I'd throw together a little "real world" example of where this could be useful. Have you ever seen a plugin or other JavaScript effect where you click on an image and it "grows in place"? I'll call it Magic Zoom because I like giving lame names to things. This is how it might work:

  1. Have a grid of thumbnail size images (keeps page load size down)
  2. When a thumbnail is clicked...
  3. Load the full size image directly over top the thumbnail, scaled down to the exact same size
  4. Animate the new full size image up to it's original size
  5. During the animation, keep the image centered over the thumbnail
  6. Click to close
HTML of gallery

The gallery is simply anchor tags that link to the large version, and within, image tags of the thumbnails. Without JavaScript, still totally functional.

<div class="gallery">

	<a href="http://farm4.static.flickr.com/3329/4556228155_7ce08c45a3.jpg">
	  <img src="http://farm4.static.flickr.com/3329/4556228155_7ce08c45a3_m.jpg" alt="" />
	</a>
	
	<!-- More... -->
	
</div>
jQuery JavaScript
$(function() {

    var $el;

    $(".gallery a").live("click", function() {    
     
        $el = $(this);
    
        $("<img />", {
        
            "src": $el.attr("href"),
            "class": "larger"
        
        }).load(function() {
        	        
            $(this)
                .appendTo("body")
                .width($el.find("img").width())
                .position({
                    "of": $el.find("img"),
        			"my": "center center",
        			"at": "center center"
			     })
                .animate({
                    width: 500, // width of large image
                    }, {
                        "duration": 1000, // 1000 = 1 second
                        "easing": "easeOutQuad",
                        "step": function(i) {
                            $(this).position({
                                "of": $el.find("img"),
                    			"my": "center center",
                    			"at": "center center",
                    			"collision": "fit"
            			     })
                        }
                    
                    }
                )
        });
        
        return false;
        
    });

	$(".larger").live("click", function() {
	    $el = $(this);
		$el.fadeOut(400, function() {
			$el.remove();
		})
	});

});

The interesting concept here is the "step" parameter for the animate function. You can give that parameter a function, and that function will run on every single keyframe of the animation. For us, that means we will use the position function to make sure the large image is still centered over it's thumbnail.

View Demo   Download Files

Yeah... the growing of the images is a little shaky. If anyone has any ideas there, let me know.

Collision detection!

Being able to set elements relative to other element with such simple syntax and little code is awesome, but what really sets this position utility above and beyond is collision detection.

What if where we tell the element to be ends up being outside the browser window? That could be a problem, depending on the situation. Take our Magic Zoom example. Theoretically the reason people are clicking the images to see a larger version is because they actually are interested in photo and want to see it larger in more detail. It doesn't help them if the image is along the left edge of the page and gets cut off as the new one grows.

Dealing with this problem is extremely easy with the position function. All we need to do is add the collision parameter with the value "fit" and the position function will ensure that whatever it is positioning is never outside the window.


By default, the larger images try to grow remaining centered over the thumbnail.

Should growing the larger image push it outside the browser window, the position utility will detect that and grow the image inward instead.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值