我前段时间寻求帮助,通过使用javascript和/或jquery,每次鼠标单击都会使单词出现在屏幕的随机不同位置。 我修改了一个与我共享的代码,但是它不起作用,而且我找不到问题。
这是我在HTML中得到的:
<link rel="stylesheet" href="css.css">
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<header>
<h4>Here is everywhere</h4>
<h5>(it depends where you are)</h5>
</header>
<div class="here">
<p>Here!</p>
</div>
<button>
click me!
</button>
<script src="javascript.js" type="application/javascript"> </script>
</body>
</html>
这是我的CSS:
@font-face {
font-family: Helvetica;
src: url(Helvetica CE Regular.ttf);
}
h4, h5, p {
font-family: helvetica;
text-transform: uppercase;
font-weight: bold;
}
h4, h5{
color: #FFF;
}
h4{
font-size: 51px;
line-height:40px;
}
p{
margin:0;
padding:0;
}
header{
background-color:#000;
width: 100vw;
height:16vh;
margin:0;
padding:0;
overflow: hidden;
}
body{
width: 100vw;
margin:0;
padding:0;
overflow: hidden;
}
.here {
position: fixed;
top: 50%;
left: 50%;
background: red;
padding: 1em;
color: white;
font-weight: bold;
}
这是我的Java和JQuery:
var按钮; button = document.getElementById('button');
$('button').click(function(){
$('.here').css({
top: (100 * Math.random()).toString() + "%",
left: (100 * Math.random()).toString() + "%",
})
})
答案 0 :(得分:3)
一个可能的原因是您的代码在DOM完全加载之前正在运行。用$(document).ready(function(){
包装代码,这将确保仅在DOM完全加载后才执行放置在内部的代码。
$(document).ready(function(){
var button;
button = document.getElementById('button');
$('button').click(function(){
$('.here').css({
top: (100 * Math.random()).toString() + "%",
left: (100 * Math.random()).toString() + "%",
});
});
});
@font-face {
font-family: Helvetica;
src: url(Helvetica CE Regular.ttf);
}
h4, h5, p {
font-family: helvetica;
text-transform: uppercase;
font-weight: bold;
}
h4, h5{
color: #FFF;
}
h4{
font-size: 51px;
line-height:40px;
}
p{
margin:0;
padding:0;
}
header{
background-color:#000;
width: 100vw;
height:16vh;
margin:0;
padding:0;
overflow: hidden;
}
.here {
position: fixed;
top: 50%;
left: 50%;
background: red;
padding: 1em;
color: white;
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>Here is everywhere</h4>
<h5>(it depends where you are)</h5>
<div class="here">
<p>Here!</p>
</div>
<button>
click me!
</button>
答案 1 :(得分:1)
尝试像这样将jQuery包装在$(document).ready()
中:
$(document).ready(function(){
$('button').click(function(){
$('.here').css({
top: (100 * Math.random()).toString() + "%",
left: (100 * Math.random()).toString() + "%",
});
});
});