Ajax实现弹窗宽度从px转换为em/vh/vw/%等单位的方法
弹窗多单位宽度支持解决方案
问题分析
原代码仅支持px作为弹窗宽度单位,无法适配em、vh、vw、%等响应式单位,核心原因是代码中把提取到的宽度值强制转为了Number类型,导致单位被剥离,无法生效。
修改方案
1. 调整宽度提取与赋值逻辑
移除将宽度转为数字的操作,直接保留包含单位的完整字符串作为宽度值:
// 原代码: // $('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend(...) // 修改为: $('#' + popID).fadeIn().css({ 'width': popWidth }).prepend('<a href="#" class="close">Close</a>');
2. 修正居中计算时机
使用相对单位时,弹窗宽度需在元素完全显示后才能准确计算,因此将居中逻辑移到fadeIn的回调函数中:
$('#' + popID).fadeIn(function() { // 元素显示后再计算居中边距 var popMargTop = $(this).height() / 2; var popMargLeft = ($(this).width() + 80) / 2; $(this).css({ 'margin-top': -popMargTop, 'margin-left': -popMargLeft }); }).css({ 'width': popWidth }).prepend('<a href="#" class="close">Close</a>');
3. 替换过时的live方法
jQuery的live()已废弃,改用on()方法进行事件委托:
// 原代码: // $('a.close, #fade').live('click', function() { ... }) // 修改为: $(document).on('click', 'a.close, #fade', function() { $('#fade , .popup_block').fadeOut(function() { $('#fade, a.close').remove(); }); return false; });
4. 更新HTML链接
现在可以直接在链接中使用任意合法CSS单位:
<a href="#?w=50%" rel="about" class="poplight">about</a> / <a href="#?w=30em" rel="writing" class="poplight">writer</a> / <a href="#?w=80vw" rel="code" class="poplight">coder</a>
修改后的完整代码
JavaScript部分
$(document).ready(function() { $('a.poplight[href^=#]').click(function() { var popID = $(this).attr('rel'); var popURL = $(this).attr('href'); var query= popURL.split('?'); var dim= query[1].split('&'); var popWidth = dim[0].split('=')[1]; // 保留完整的数值+单位字符串 $('#' + popID) .css({ 'width': popWidth }) .prepend('<a href="#" class="close">Close</a>') .fadeIn(function() { // 显示后计算居中边距 var popMargTop = $(this).height() / 2; var popMargLeft = ($(this).width() + 80) / 2; $(this).css({ 'margin-top': -popMargTop, 'margin-left': -popMargLeft }); }); $('body').append('<div id="fade"></div>'); $('#fade').css({'filter': 'alpha(opacity=80)'}).fadeIn(); return false; }); // 关闭弹窗逻辑 $(document).on('click', 'a.close, #fade', function() { $('#fade , .popup_block').fadeOut(function() { $('#fade, a.close').remove(); }); return false; }); });
HTML部分
<a href="#?w=50%" rel="about" class="poplight">about</a> / <a href="#?w=30em" rel="writing" class="poplight">writer</a> / <a href="#?w=80vw" rel="code" class="poplight">coder</a> <div id="about" class="popup_block"></div> <div id="writing" class="popup_block"></div> <div id="code" class="popup_block"></div>
内容的提问来源于stack exchange,提问作者arrow
相关产品推荐
相关产品推荐

