Last active
October 13, 2016 18:28
-
-
Save monjer/9426447 to your computer and use it in GitHub Desktop.
jQuery.iframe.js,simple jQuery plugin for iframe element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simple jQuery plugin for iframe element . | |
* | |
* Note: The parent doc and iframe's embed doc must be in the same origin , | |
* Domains, protocols and ports must match. | |
* | |
* reference: | |
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript | |
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe | |
* | |
* @author manjun.han | |
* @date 2014.3.8 | |
*/ | |
(function($){ | |
/** | |
* determine if the dom contained in jQuery wapper object is HTMLIFrameElement. | |
* | |
* @param {Object} The jQuery wapper object | |
* @return {Boolean} true,the dom is HTMLIFrameElement | |
*/ | |
function validateIframe($el){ | |
if($el.length == 0 || $el[0].nodeName.toLowerCase() != 'iframe'){ | |
return false ; | |
} | |
return true ; | |
} | |
/** | |
* Get the window object of the HTML doc embed in iframe. | |
* | |
* @return {Object} window object of embed HTML doc. | |
*/ | |
$.fn.iframeWin = function(){ | |
return validateIframe(this) ? this[0].contentWindow : null ; | |
}; | |
/** | |
* Get the document object of the HTML doc embed in iframe. | |
* | |
* @return {Object} document object of embed HTML doc. | |
*/ | |
$.fn.iframeDoc = function(){ | |
return validateIframe(this) ? (this[0].contentDocument || this[0].contentWindow.document) : null ; | |
}; | |
/** | |
* Set the selected iframe element's height to its content doc's height. | |
* | |
* @return jQuery wapper object. | |
*/ | |
$.fn.iframeAutoHeight = function(){ | |
this.each(function(index , el){ | |
var $el = $(el) ; | |
if(!validateIframe($el)){ | |
return ; | |
} | |
var loaded = $el.data("iframe-loaded"); | |
if(loaded){ | |
$el.css("height" , $($el.iframeDoc()).height()+"px"); | |
}else{ | |
$el.bind("load" , function(){ | |
$el.data("iframe-loaded" , true).iframeAutoHeight(); | |
}); | |
} | |
}); | |
return this ; | |
}; | |
})($); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
1.
$.iframeDoc
,$.iframeWin
2.$.iframeAutoHeight