天天看點

js設定水印在指定視窗無規則出現

<!DOCTYPE html>
<html>
<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>對象在視窗無規則浮動</title>
		<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
        <link rel="stylesheet" type="text/css" href="reset.css"/>
<style>

div{
    position:absolute;
}

</style>
</head>
<body>

    <div id="div" style="width: 800px;height:500px;background: pink;margin-top:50px;margin-left:100px;">
		
		<div id="divImg" style="background:red;width:30;height:30;">
			<p>劉美嬌</p>
		</div>
    
    </div>
    
    <button type="button" onclick="start();">開始</button>
	<button type="button" onclick="end();">結束</button>
  
<script language="javascript" type="text/javascript">
	
	
	    
	function floatimg() {
			
		//擷取div左上角坐标,即距離body的距離,浮動對象起始位置
		var x = $("#div").offset().left,
			y = $("#div").offset().top;
			
		//擷取div自身的寬高,帶内邊距
		var a = $("#div").innerWidth(),
		    b = $("#div").innerHeight();
			
		//擷取浮動對象在div内右下邊最大X和Y的坐标值
		var w = a-30,
		    h = b-30;
		
		//随機産生坐标x和坐标Y的值(從左上角到右下角最大X和Y的坐标随機)
		ranx = Math.floor(Math.random()*(w-x+1)+x);
		rany = Math.floor(Math.random()*(h-y+1)+y);
		
		//擷取随機浮動對象,給對象樣式确定坐标
		var img1 = document.getElementById("divImg");
		img1.style.left = ranx + "px";
		img1.style.top = rany + "px";
		
		$("#divImg").show();
	
	}
	
	function start(){
		
		s = setInterval(function(){
			
			// setTimeout("floatimg()", 500);
			floatimg();
            console.count('other 已經執行');
		},Math.round(Math.random()* 10000));
		
	}
	
	function end(){
		clearInterval(s);
		$("#divImg").hide();
		console.log('停止了');
	}
		
</script>
</body>
</html>