JavaScript代码给出错误。我搜索了但找不到。也许我使用的jquery脚本有问题。
错误:
未捕获的TypeError:无法读取null的属性'querySelector'
var btn = document.querySelector('.btn');
var btnFront = btn.querySelector('.btn-front'),
btnYes = btn.querySelector('.btn-back .yes'),
btnNo = btn.querySelector('.btn-back .no');
btnFront.addEventListener('click', function(event) {
var mx = event.clientX - btn.offsetLeft,
my = event.clientY - btn.offsetTop;
var w = btn.offsetWidth,
h = btn.offsetHeight;
var directions = [{
id: 'top',
x: w / 2,
y: 0
},
{
id: 'right',
x: w,
y: h / 2
},
{
id: 'bottom',
x: w / 2,
y: h
},
{
id: 'left',
x: 0,
y: h / 2
}
];
directions.sort(function(a, b) {
return distance(mx, my, a.x, a.y) - distance(mx, my, b.x, b.y);
});
btn.setAttribute('data-direction', directions.shift().id);
btn.classList.add('is-open');
});
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="../CSS/LoginCSS.css">
<script src="../JavaScript/LoginJS.js"></script>
</head>
<body>
<div class="btn">
<div class="btn-back">
<p>Are you sure you want to do that?</p>
<button class="yes">Yes</button>
<button class="no">No</button>
</div>
<div class="btn-front">Delete</div>
</div>
</body>
感谢您的帮助。最好的祝福。
答案 0 :(得分:0)
我刚刚添加了$( document ).ready(function()
,它就发生了。
$( document ).ready(function() {
var btn = document.querySelector( '.btn' );
var btnFront = btn.querySelector( '.btn-front' ),
btnYes = btn.querySelector( '.btn-back .yes' ),
btnNo = btn.querySelector( '.btn-back .no' );
btnFront.addEventListener( 'click', function( event ) {
var mx = event.clientX - btn.offsetLeft,
my = event.clientY - btn.offsetTop;
var w = btn.offsetWidth,
h = btn.offsetHeight;
var directions = [
{ id: 'top', x: w/2, y: 0 },
{ id: 'right', x: w, y: h/2 },
{ id: 'bottom', x: w/2, y: h },
{ id: 'left', x: 0, y: h/2 }
];
directions.sort( function( a, b ) {
return distance( mx, my, a.x, a.y ) - distance( mx, my, b.x, b.y );
} );
btn.setAttribute( 'data-direction', directions.shift().id );
btn.classList.add( 'is-open' );
} );
btnYes.addEventListener( 'click', function( event ) {
btn.classList.remove( 'is-open' );
} );
btnNo.addEventListener( 'click', function( event ) {
btn.classList.remove( 'is-open' );
} );
function distance( x1, y1, x2, y2 ) {
var dx = x1-x2;
var dy = y1-y2;
return Math.sqrt( dx*dx + dy*dy );
}
});