JavaScript-前端常用代码

图片[1]-JavaScript-前端常用代码-不念博客

禁止右键

<script type="text/javascript">
document.body.oncontextmenu=document.body.ondragstart= document.body.onselectstart=document.body.onbeforecopy=function(){return false;};
document.body.onselect=document.body.oncopy=document.body.onmouseup=function(){document.selection.empty();};
</script>

禁止F12

 <script type="text/javascript">
     document.oncontextmenu = function () { return false; };
        document.onkeydown = function () {
            if (window.event && window.event.keyCode == 123) {
                event.keyCode = 0;
                event.returnValue = false;
                return false;
            }
        };
</script>

返回上一页

<a href="#" onClick="javascript :history.back(-1);">返回上一页</a>

返回顶部

javascript:scroll(0,0)

自动获取当前年份

<script>document.write(new Date().getFullYear());</script>

同一个页面多视频时只能同时播放一个视频

<script>
var au=document.getElementsByTagName("video");
for(var i=0;i<au.length;i++){
au[i].addEventListener("playing", function(){
var this1=this;
this.play();
for(var b=0;b<au.length;b++){
var this2=au[b];
if(this1!==this2){
this2.pause();
}
}
});
}
</script>

自动获取当前日期

<script>
     var obj=new Date();
     var year=obj.getFullYear();
     var month=obj.getMonth()+1;
     var day=obj.getDate();
     document.write("今天是:"+year+"年"+month+"月"+day+"日")
</script>

替代A标签链接

onclick="location='链接地址'"

控制链接在新的页面打开

onclick="window.open('链接地址')"

设置浏览器弹窗内容

onclick="alert('文字内容')"

点击按钮复制指定内容

<div>
    <span id="user_ref_id">复制内容</span>
    <input style="margin-left: 30px;" type="button" onclick="cp(document.getElementById('user_ref_id'));" value="复制给好友" >
</div>
<script>
        function selectText(x) {
            if (document.selection) {
                var range = document.body.createTextRange();
                range.moveToElementText(x);
                range.select();
            } else if (window.getSelection) {
                var selection = window.getSelection();
                var range = document.createRange();
                selection.removeAllRanges();
                range.selectNodeContents(x);
                selection.addRange(range);
            }
        }
        function cp(x) {
            selectText(x);
            document.execCommand("copy");
            alert("复制成功,快去分享好友吧")
        }
</script>

改变HTML元素的内容

<p id="demo">
JavaScript 能改变 HTML 元素的内容。
</p>
<script>
function myFunction()
{
x=document.getElementById("demo");  // 找到元素
x.innerHTML="Hello JavaScript!";    // 改变内容
}
</script>
<button type="button" onclick="myFunction()">点击这里</button>

程序运行时间

<script language="JavaScript"  type="text/javascript">
var urodz = new Date("2021-01-18");
var now = new Date();
var ile = now.getTime() - urodz.getTime();
var dni = Math.floor(ile / (1000 * 60 * 60 * 24));
document.write(+ dni)
</script>
© 版权声明
THE END