如何让ZURB twentytwenty jQuery滑块拖拽到两端时切换div显示属性
实现方案
方法1:直接修改插件源码(最适配你的需求)
你提到的getSliderPercentage方法返回值就是滑块当前位置的百分比,范围是0(最左侧)到1(最右侧),你只需要在插件内部调用该方法更新滑块位置的逻辑后,新增判断逻辑即可:
- 打开
jquery.twentytwenty.js文件,找到调用getSliderPercentage的代码段,通常位于处理拖拽移动的函数内 - 在获取到
sliderPercentage返回值后,新增如下判断代码:
// 原有代码,用来获取滑块位置百分比 var sliderPercentage = getSliderPercentage(positionX, positionY); // 原有更新滑块位置、图片裁剪区域的代码不用动,直接在后面加下面的逻辑 // 新增hero切换逻辑 if (sliderPercentage === 1) { // 滑块拖到最右侧 document.querySelector('.hero').style.display = 'none'; document.querySelector('.hero2').style.display = 'block'; document.querySelector('.hero3').style.display = 'none'; } else if (sliderPercentage === 0) { // 滑块拖到最左侧 document.querySelector('.hero').style.display = 'none'; document.querySelector('.hero2').style.display = 'none'; document.querySelector('.hero3').style.display = 'block'; } else { // 滑块位于中间区域,显示默认.hero document.querySelector('.hero').style.display = 'block'; document.querySelector('.hero2').style.display = 'none'; document.querySelector('.hero3').style.display = 'none'; }
方法2:不修改插件源码,外部监听拖拽事件实现
如果你不想改动插件原文件,可以在你自己的业务代码里加监听逻辑,监听滑块的拖拽动作,实时计算位置百分比判断:
// 先获取twentytwenty容器、滑块元素 const $twContainer = $('.twentytwenty-container'); const $slider = $twContainer.find('.twentytwenty-handle'); const containerWidth = $twContainer.width(); // 监听鼠标/触摸移动事件 $twContainer.on('mousemove touchmove', function(e) { // 获取滑块当前偏移量 const sliderOffset = $slider.offset().left - $twContainer.offset().left; const percentage = sliderOffset / containerWidth; // 百分比取整判断,避免精度问题 const pct = Math.round(percentage * 100) / 100; if (pct >= 0.99) { // 接近最右侧 $('.hero').hide(); $('.hero2').show(); $('.hero3').hide(); } else if (pct <= 0.01) { // 接近最左侧 $('.hero').hide(); $('.hero2').hide(); $('.hero3').show(); } else { $('.hero').show(); $('.hero2').hide(); $('.hero3').hide(); } });
注意事项
- 可以根据实际交互需求调整阈值,比如不用严格等于0或1,设置大于0.98就算最右侧,小于0.02就算最左侧,避免拖拽到边缘时判断不灵敏
- 初始状态下记得给
.hero2和.hero3设置display: none,默认只显示.hero
内容的提问来源于stack exchange,提问作者Overflow_hidden
相关产品推荐
相关产品推荐

