WordPress移动端Read More文本功能异常问题求助
解决Read More脚本收起时强制设置100px高度的问题
你的问题出在脚本收起文本时硬编码了100px的高度,这直接覆盖了你通过CSS(尤其是移动端媒体查询)为不同区块设置的自定义高度。下面是修改后的脚本,完美适配你多区块、多设备的自定义高度需求:
// 初始化时提前存储每个文本块的默认高度(对应你CSS里设置的高度) jQuery('.read-more__text').each(function() { const defaultHeight = window.getComputedStyle(this).height; jQuery(this).data('defaultHeight', defaultHeight); }); jQuery('.read-more__btn').click(function(){ const $textBlock = jQuery(this).siblings(".read-more__text"); if ($textBlock.hasClass("show")) { // 收起逻辑:用存储的默认高度替代硬写的100px jQuery(this).removeClass("up").text("Read More"); $textBlock.animate({ height: $textBlock.data('defaultHeight') }, 1000, function() { // 动画结束后清除行内height,让CSS规则重新生效 jQuery(this).css('height', ''); }); $textBlock.removeClass("show"); } else { // 展开逻辑保持不变 $textBlock.addClass("show"); $textBlock.animate({ height: $textBlock.get(0).scrollHeight }, 1000, function(){ jQuery(this).height('auto'); }); jQuery(this).addClass("up").text("Read Less"); } });
关键修改说明:
- 初始化阶段通过
window.getComputedStyle获取每个文本块的实际计算高度(也就是你CSS里写的高度,包括移动端媒体查询的设置),并存在元素的data属性里 - 收起动画时不再用固定的
100px,而是调用存储的默认高度,确保不同区块、不同设备的自定义高度都能生效 - 动画结束后清除行内的
height样式,避免后续窗口大小变化时,行内样式覆盖CSS的响应式设置
如果你不想提前初始化存储高度,也可以在每次点击收起时直接获取计算高度(效果一样),把收起部分的代码改成这样:
if ($textBlock.hasClass("show")) { jQuery(this).removeClass("up").text("Read More"); // 实时获取当前的计算高度(CSS设置的高度) const defaultHeight = window.getComputedStyle($textBlock[0]).height; $textBlock.animate({ height: defaultHeight }, 1000, function() { jQuery(this).css('height', ''); }); $textBlock.removeClass("show"); }
内容的提问来源于stack exchange,提问作者baxi
相关产品推荐
相关产品推荐

