mouseenter和mouseleave

摘自jQuery的一段代码:

var withinElement = function(event) {
	// Check if mouse(over|out) are still within the same parent element
	var parent = event.relatedTarget;
	// Traverse up the tree
	while ( parent && parent != this )
		try { parent = parent.parentNode; }
		catch(e) { parent = this; }

	if( parent != this ){
		// set the correct event type
		event.type = event.data;
		// handle event if we actually just moused on to a non sub-element
		jQuery.event.handle.apply( this, arguments );
	}
};

附带event.relatedTarget的实现方法:

// Add relatedTarget, if necessary
if ( !event.relatedTarget && event.fromElement )
	event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;

用jQuery判断一个元素是否显示

用jQuery判断一个元素是否显示:$(element).is(“:visible”)

类似的,判断一个元素是不是第一个子元素:$(element).is(“:first-child”)

IE6中select元素z-index的bug

通常的情况下,IE6中的select元素永远是在最上面的,即使覆盖在它上面的元素的z-index再大也不起作用。比如说有个id为div1的元素绝对定位在select元素的上面。这里假设div1的z-index比select的大,但在IE6里看上去还是select在上面,div1并不能覆盖住它。为了解决这个问题,只能在div1和select中间插入一个和div1的位置以及大小一样的iframe来达到覆盖select的效果。

网上有个叫bgiframe的jQuery插件可以达到这个效果。拿上面的例子来说,它动态的在div1里插入一个透明的iframe,iframe的尺寸是用IE特有的CSS expression计算的,这么做的好处在于iframe随时都可以保持和div1同样大小,缺点是CSS expression太占资源了,可能会导致浏览器假死,如果覆盖在select上的元素的尺寸在运行时不会改变的话,就没必要用CSS expression。所以把bgiframe的代码改了一下。

改过之后的代码,记录一下:

(function($){
  $.fn.bgIframe = $.fn.bgiframe = function(s) {
    if ($.browser.msie && /6.0/.test(navigator.userAgent)) {
      s = $.extend({
        top    : 'auto',
        left    : 'auto',
        width   : 'auto',
        height  : 'auto',
        src     : 'javascript:false;'
      }, s || {});
      var prop = function(n) {
        return n&&n.constructor==Number?n+'px':n;
      };
      return this.each(function() {
        if ( $('> iframe.bgiframe', this).length == 0 ) {
          var iframe = $('<iframe frameborder="0" tabindex="-1"></iframe>')
          .addClass("bgiframe")
          .css({
            display: 'block',
            position: 'absolute',
            zIndex: '-1',
            opacity: 0,
            top: s.top === 'auto'?
              ((this.clientTop || 0)*-1 + 'px'): prop(s.top),
            left: s.left === 'auto'?
              ((this.clientLeft || 0)*-1 + 'px'): prop(s.left),
            width: s.width === 'auto'?
              (this.offsetWidth + 'px'): prop(s.width),
            height: s.height === 'auto'?
              (this.offsetHeight + 'px'): prop(s.height)
          })
          .insertBefore(this.firstChild);
        }
      });
    }
    return this;
  };
})(jQuery);

relatedTarget, fromElement, toElement

记录一下。原文:http://www.quirksmode.org/js/events_mouse.html#relatedtarget

W3C在mouseover和mouseout事件中添加了relatedTarget属性。在mouseover事件中,它表示鼠标来自哪个元素,在mouseout事件中,它指向鼠标去往的那个元素。

而Microsoft添加了两个属性:

  • fromElement在mouseover事件中表示鼠标来自哪个元素。
  • toElement在mouseout事件中指向鼠标去往的那个元素。

跨浏览器的脚本

如果你想知道鼠标来自哪个元素在mouseover事件中,你可以这样写:

function doSomething(e) {
	if (!e) var e = window.event;
	var relTarg = e.relatedTarget || e.fromElement;
}

如果你想知道鼠标去往哪个元素在mouseout事件中,你可以这样写:

function doSomething(e) {
	if (!e) var e = window.event;
	var relTarg = e.relatedTarget || e.toElement;
}

elem.style.left与elem.offsetLeft的区别

elem.style.left是元素的最左边(包括元素的margin-left)到offsetParent左边padding(包括左边padding)的距离。

用公式简单的表示一下两者的关系:elem.offsetLeft = elem.style.left + elem.style.marginLeft

在IE8下:
elem.offsetLeft = elem.style.left + elem.style.marginLeft + elem.offsetParent.borderLeftWidth

在IE7下:
elem.offsetLeft = elem.style.left + elem.style.marginLeft + elem.offsetParent.borderLeftWidth + elem.offsetParent.marginLeftWidth

在IE6下:
elem.offsetLeft = elem.style.left + elem.style.marginLeft + elem.offsetParent.paddingLeftWidth + elem.offsetParent.borderLeftWidth + elem.offsetParent.marginLeftWidth

记录一下,如何取得元素的”计算出的样式”。

function getCurrentStyle(elem, style) {
	return window.getComputedStyle
			? window.getComputedStyle(elem, null)[style]
			: elem.currentStyle[style];
}

预览本地图片的二三事

到目前为止,只有IE和FF可以预览本地图片。IE下可以直接浏览本地图片,通过input[type=file]的value属性就可以取到本地图片的路径。而在FF下,有getAsDataURL的方法可以生成图片的DataURL,然后赋值给img标签。

IE下的演示:

document.getElementById("upload").onchange = function() {
	document.getElementById("image").src = this.value;
}

FF下的演示:

document.getElementById("upload").onchange = function() {
	document.getElementById("image").src = this.files[0].getAsDataURL();
}

滚动页面到某个元素

MSDN上搬过来的,记录一下。

Syntax

object.scrollIntoView( [bAlignToTop])

Parameters

bAlignToTop Optional. Boolean that specifies one of the following values:
true
Default. Scrolls the object so that top of the object is visible at the top of the window.
false
Scrolls the object so that the bottom of the object is visible at the bottom of the window.

Return Value

No return value.

Remarks

The scrollIntoView method is useful for immediately showing the user the result of some action without requiring the user to manually scroll through the document to find the result.
Depending on the size of the given object and the current window, this method might not be able to put the item at the very top or very bottom, but will position the object as close to the requested position as possible.

Example

This example uses the scrollIntoView method to underline the content of the document’s fifth paragraph and scroll it into view at the top of the window.

var coll = document.all.tags("P");
if (coll.length >= 5) {
  coll(4).style.textDecoration = "underline";
  coll(4).scrollIntoView(true);
}

星级评价控件(jQuery版)

前几天写一个打分的UI,没有实现功能,现在把功能加入进来,并且用jQuery封装一下。

演示地址:http://www.zhoumingzhi.com/wp-content/uploads/2010/01/rating/demo.html

下载地址:http://code.google.com/p/rating-widget/downloads/list

用法:

$(function () {
    $(".ui-rating").rating({
        "activate": 7,
        "total": 10,
        "select": function (event, ui) {
        },
        "change": function (event, ui) {
        }
    });
});

用一个空的块元素标签实例化即可,最好是用div。

参数说明:

参数 类型 说明
total number/string 级别总数,通常来说就是指星星的个数,除非是用半个星星表示一个等级。
activate number/string 当前选中的级别,一般用来指示所有用户选的平均值。
select function(event, ui) 处理点击事件的函数。event参数代表事件,ui.level表示选中的级别。
change function(event, ui) 这个函数在鼠标移动时被触发。event参数代表事件,ui.level表示鼠标划过的级别。

方法说明:

$(".ui-rating").rating("option", "activate", 5);
$(".ui-rating").rating("enable");
$(".ui-rating").rating("disable");

activate方法有一个参数,表示要设定的等级。

扩展jQuery选择器


jQuery本身提供了一些强大的带有冒号的选择器,比如:first, :even这些。但是这些还满足不了需求的话,可以自己扩展一个选择器。比如要选择一些文本为”hello world”的链接,用jQuery自带的:contain是可以,但是它会把”hello world, I’m Michael”也选择进来,不够精确。于是我们就自己定义一个:text

$.extend($.expr[':'], {
    text: function(a, i, m) {
        return ((a.textContent
        || a.innerText
        || jQuery(a).text()
        || "") === m[3]);
    }
});

用$(“a:text(‘hello world’)”)来调用上面的方法,函数里的m[3]就是输入的参数,在这里为”hello world”。

测试一下:猛击我

  • hello world
  • hello world
  • hello world, I’m Michael.
  • hello world
  • hello world, I’m Leo.

[转贴] JS中如何判断字符串类型的数字

var str = "37";
var n = Number(str);
if (!isNaN(n))
{
    alert("是数字");
}

注意:在 JavaScript 中,对于省略写法(如:”.3″、”-.3″)、科学计数法(如:”3e7″、”3e-7″)、十六进制数(如:”0xFF”、”0x3e7″)均被认定为数字格式,这类字符串都可以用 Number 转化成数字。

isNaN 返回一个 Boolean 值,指明提供的值是否是 NaN ,NaN 的意思是 not a number(不是一个数字)。

语法:isNaN(numValue)