jQuery基于函数重载实现自定义Alert函数样式的方法


本文实例讲述了jQuery基于函数重载实现自定义Alert函数样式的方法。分享给大家供大家参考,具体如下:

(function(){
window.alert = function(text) {
 text=text.toString().replace(/\\/g,'\\').replace(/\n/g,'<br />').replace(/\r/g,'<br />'); //解析alert内容中的换行符
 var alertdiv='<div id="alertdiv" style="position:absolute; display:none ; overflow:hidden; padding:10px 10px 8px; top: 50%; left: 50%; text-align:center; line-height:22px; background-color:#DDE4EE; border:1px solid #ccc">'+text+'<br /><input type="submit" name="button" id="button" value="确定" style="margin-top:8px;" onclick="$(this).parent().remove(); "/></div>'; //自定义div弹窗
 $(document.body).append(alertdiv); //动态加载div
 $("#alertdiv").css({"margin-left":$("#alertdiv").width()/2*(-1)-20,"margin-top":$("#alertdiv").height()/2*(-1)-20}); //设置偏移数值,实现div居中
 $("#alertdiv").show(); //显示
};
})();

注:以上代码可自适应alert内容长度,支持换行符,调用时与原始alert函数无异。

完整示例代码如下:

<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.10.2/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
(function(){
window.alert = function(text) {
 text=text.toString().replace(/\\/g,'\\').replace(/\n/g,'<br />').replace(/\r/g,'<br />'); //解析alert内容中的换行符
 var alertdiv='<div id="alertdiv" style="position:absolute; display:none ; overflow:hidden; padding:10px 10px 8px; top: 50%; left: 50%; text-align:center; line-height:22px; background-color:#DDE4EE; border:1px solid #ccc">'+text+'<br /><input type="submit" name="button" id="button" value="确定" style="margin-top:8px;" onclick="$(this).parent().remove(); "/></div>'; //自定义div弹窗
 $(document.body).append(alertdiv); //动态加载div
 $("#alertdiv").css({"margin-left":$("#alertdiv").width()/2*(-1)-20,"margin-top":$("#alertdiv").height()/2*(-1)-20}); //设置偏移数值,实现div居中
 $("#alertdiv").show(); //显示
};
})();
</script><input type="submit" name="button" id="button" value="点击弹出alert自定义窗口" onclick='alert("这是alert弹窗\n支持\\n换行符")'/>

运行效果截图如下:

更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery扩展技巧总结》、《jQuery常用插件及用法总结》、《jQuery拖拽特效与技巧总结》、《jQuery表格(table)操作技巧汇总》、《jquery中Ajax用法总结》、《jQuery常见经典特效汇总》、《jQuery动画与特效用法总结》及《jquery选择器用法总结》

希望本文所述对大家jQuery程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3