1.链接文本 -> 可点击的超链接
var text = "我是链接文本https://www.baidu.com"
var re = /(http(s)?:\/\/[\w.\/]+)(?![^<]+>)/gi;
text = text.replace(re, "<a target='_blank' href='$1'>$1</a>");
2.禁止页面滚动及解除禁止(支持移动端和网站端)
const forbidScroll = (e) => {
e.preventDefault && e.preventDefault();
e.returnValue = false;
e.stopPropagation && e.stopPropagation();
return false;
}
const addListener = () => {
window.addEventListener('mousewheel', forbidScrolll)
window.addEventListener('touchmove', forbidScroll, { passive: false })
}
const removeListener = () => {
window.removeEventListener("mousewheel", forbidScrolll);
window.removeEventListener("touchmove", forbidScrolll, { passive: false });
}
3.将 dom 元素转成图片(适配移动端)
这里借助于
html2canvas.js
这个库,html2canvas 库地址,文档地址, 我用的是v1.0.0-rc.3
版本的。这里在适配移动端的时候,iOS
系统在图片转化的过程中,如果滑动了页面,转成的图片布局是乱的,这里我用了在转化完成之前禁止滚动,完成后再解除。iOS 12.2
以上系统,如果dom
元素有img
标签元素,最终转成的图片会出现img
标签所对应的图片是空白的,这里我的解决办法是将img
标签改成span
背景图片来表示。
“很是苦恼,在网上查了一大堆资料,用了一天的时间,才达到领导的要求,网站、安卓一切正常,只有苹果手机会出现这种情况,而且是高版本的。气人”
const convertImg = () => {
var node = document.getElementById("poster-container-view"); //要转换成图片的 dom 容器
html2canvas(node, { backgroundColor: '#433da0' }).then(canvas => {
app.dataUrl = canvas.toDataURL(); //这是最终的图片地址,此处是直接更改的 vue 中实例的图片地址。
window.removeEventListener("mousewheel", forbidScroll);
window.removeEventListener("touchmove", forbidScroll, { passive: false });
app.loading = false;
console.log("海报已经生成好了...")
})
}
const initPoster = () => {
window.addEventListener('mousewheel', forbidScroll)
window.addEventListener('touchmove', forbidScroll, { passive: false })
convertImg();
}
4. audio 标签自动播放音乐,iOS 微信端无效问题
一个用于在微信使用的 h5 页面,设置一个标签 audio,自动播放。pc 和安卓都已测试可以自动播放,但是在 iPhone 上无声音,推测audio 标签在iOS 系统无法自动播放。解决办法如下:
let audio = document.getElementById("bgm");
document.addEventListener("WeixinJSBridgeReady", function () {
audio.play();
}, false);
5. 出现在可视区域中的动画元素播放,否则不播放
有这样一个需求,对于出现在当前用户可以看到的页面上的元素或可视窗口上方的,播放动画元素,下方的,在滚动页面的同时,如果出现在了窗口中,再去加载,否则不加载。解决方法是,给所有的动画元素加一个统一的 class 名(animation),具体代码如下:
<img class="feedback-logo animation animation-slideInDown" src="./images/feedback__logo.png" />
const openAnimation = ()=>{
$(".animation").each(function(){
let scroll_top = document.documentElement.scrollTop || document.body.scrollTop;
let client_height = document.documentElement.clientHeight;
let current_top = $(this).offset().top;
if (current_top < scroll_top || (current_top >= scroll_top && current_top < scroll_top+client_height+1)){
//可视区域及上方
$(this).css({
"animation-play-state":"running"
})
}else{
//可视区域下方
}
})
}
openAnimation(); //页面刚加载出来时,调用一次,因为此时不会走滚动事件
$("window").scroll(function(e){
openAnimation();
})
.animation{
animation-play-state: paused;
}