自定义带样式的title提示框
-
效果如下:
- 需要引入jQuery
<script src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
- 代码如下:
<ul> <ol class="styleTitle" titleParam='<span style="color: red"></h1>这是第一个带样式的</span>title<h1><span style="color: red">1</span><br/>2<br/>3<br/>4<br/>5<br/>6<br/>7<br/>8<br/>9<br/></h1>'> 第一个 </ol> <ol class="styleTitle" titleParam='<span style="color: red"></h1>这是第二个带样式的</span>title<h1>1<br/><span style="color: red">2</span><br/>3<br/>4<br/>5<br/>6<br/>7<br/>8<br/>9<br/></h1>'> 第二个 </ol> <ol class="styleTitle" titleParam='<span style="color: red"></h1>这是第三个带样式的</span>title<h1>1<br/>2<br/><span style="color: red">3</span><br/>4<br/>5<br/>6<br/>7<br/>8<br/>9<br/></h1>'> 第三个 </ol> </ul>
$(function () { //带样式的title $(".styleTitle").on("mouseenter mouseleave mousemove", function (event) { var left = event.pageX, top = event.pageY; var ele = event.target; var title = $(this).attr("titleParam"); if (title == null || title == "" || title.length < 1) { return; } var type = event.originalEvent.type; if (type == 'mouseover') { ele.title = ''; //if(title && title.length > 0){ if (title != null) { //鼠标进入显示弹框 var showEle = $('<div></div>', {html: title, class: 'showTitleBox'}).css({ position: 'absolute', top: top + 10, left: left + 10, border: '1px solid #CCC', borderRadius: '5px', background: "#CCC", fontFamily: 'SimHei', overflowY: "auto" }) showEle.appendTo('body'); } } else if (type == 'mouseout') { $('.showTitleBox').remove();//鼠标移出删除弹框 } else if (type == 'mousemove') { $('.showTitleBox').css({//跟随鼠标 top: top + 10, left: left + 10 }) } var titleBox = $(".showTitleBox"); //如果高度大于200,则限制高度 if (titleBox.height() && titleBox.height() > 200) { titleBox.height(200) } //不让title的高度超出可视区 var titleOffset = titleBox.offset(); if (titleOffset) { //可视区高度 var windowH = $(window).height(); //title距离可视区上边距离 var titleTopH = titleOffset.top - $(document).scrollTop(); //title高度 var titleH = titleBox.height(); //如果超出可视区,则缩小高度 if (titleTopH + titleH > windowH) { var newH = windowH - titleTopH - 10; //如果高度小于200,则移动title if (newH <= 200) { $('.showTitleBox').css({ top: $(document).scrollTop() - titleBox.height() + windowH, left: left + 10 }) } else { titleBox.height(newH); } } } }); //滚动title中的内容 $(".styleTitle").on("mousewheel DOMMouseScroll", function (ev) { var showTitleBox = $(".showTitleBox"); //如果title不存在,则滚动页面 if (showTitleBox.length == 0) { return true; } if (ev.type == "DOMMouseScroll") {//火狐 showTitleBox.scrollTop(showTitleBox.scrollTop() + (ev.originalEvent.detail * 40)); } else {//其他 showTitleBox.scrollTop(showTitleBox.scrollTop() - ev.originalEvent.wheelDelta); } return false; }); });
- 需要注意滚轮事件
mousewheel
和DOMMouseScroll
的区别:mousewheel
:除了火狐都兼容DOMMouseScroll
:只有火狐兼容
- 转载请注明:https://blog.xinpapa.com/2017/12/22/styletitle/