当文本过长溢出时,想要将溢出的文本隐藏起来但仍然可以滚动查看文本,但不需要显示滚动条时可以使用以下方法
html代码
<div>
<span>超长文本超长文本超长文本</span>
</div>
css样式
span{
display: block;/*flex等*/
width: 100px;
white-space: nowrap;/*文本显示在一行不换行*/
overflow-x: auto;
overflow-y: hidden;/*有的文本会因为高度设置有竖向滚动条,将其隐藏*/
}
/*隐藏滚动条 但仍能滚动 overflow需设置为auto或scoll*/
::-webkit-scrollbar {
display: none;/*或width:0px;*/
}
以上,页面显示效果就有了
js代码
如果span便签已经写在html页面里可以直接在js下写该段代码
$("span").bind('mousewheel DOMMouseScroll',function(event){ //on也可以 bind监听
let scrollText = $(this).children()
$(this).addClass("scrollmove");
//Chorme 浏览器滚轮事件
var wheel = event.originalEvent.wheelDelta;
var scroll_width = 100;
if (event.originalEvent.wheelDelta) { //判断浏览器IE,谷歌滚轮事件
if (wheel > 0) { //当滑轮向上滚动时
//alert('上滚');
$(".scrollmove").scrollLeft($(".scrollmove").scrollLeft() - scroll_width);
$(this).removeClass("scrollmove");
}
if (wheel < 0) { //当滑轮向下滚动时
//alert('下滚');
$(".scrollmove").scrollLeft($(".scrollmove").scrollLeft() + scroll_width);
//window.getSelection("span").scrollLeft($("span").scrollLeft() + scroll_width);
$(this).removeClass("scrollmove");
}
}
});
如果span是动态生成的,那么需要在页面渲染完成之后在添加该段代码,将其封装为一个函数,然后在$(function(){}最后一行调用该函数
$(function(){
//你原来的js代码
//最后一行调用该函数
evenMouse();
}
//监听
function evenMouse(){
$("span").bind('mousewheel',function(event){ //on也可以
$(this).addClass("scrollmove");
//谷歌浏览器滚轮事件
var wheel = event.originalEvent.wheelDelta;//获取事件属性值
var scroll_width = 100;
if (event.originalEvent.wheelDelta) { //判断浏览器滚轮事件
if (wheel > 0) { //当滑轮向上滚动时
$(".scrollmove").scrollLeft($(".scrollmove").scrollLeft() - scroll_width);
$(this).removeClass("scrollmove");
}
if (wheel < 0) { //当滑轮向下滚动时
$(".scrollmove").scrollLeft($(".scrollmove").scrollLeft() + scroll_width);
$(this).removeClass("scrollmove");
}
}
});
}
或者在span标签渲染结束后的js下调用该函数,注:此监听事件仅监听了谷歌浏览器的滚轮事件,如果是其他浏览器需要更改bind()里的事件并创建变量存储事件的属性值(滚轮上滚下滚),如Firefox 浏览器的 DOMMouseScroll事件,event.detail属性返回的负值上滚,正值下滚