У меня есть эта программа, в которой я создаю программное обеспечение для рисования. Когда я нажимаю клавишу Ctrl во время движения мыши, он включает ластик. Когда клавиша нажата, я хочу, чтобы курсор (в настоящее время перекрестие) не изменился. Как мне это сделать? Я пытался реализовать document.body.style.cursor = "none" и document.getElementById("canvas").style.cursor = "none", но оба не сработали. Мне нужно использовать Javascript, так что без Jquery, пожалуйста.
Это часть моего предпринятого кода:
<!doctype html>
<html lang = "en">
<head>
<style>
body {
/*
this css selector (body) tells the browser that this style block applies to ALL <body> elements on this page; just because there is only 1 <body> doesnt make any difference
*/
background-color: #c0c0c0; /* this css property sets the background colour of the entire body of the web page */
/*
the colour: #c0c0c0 uses the format RRGGBB (RR=c0, GG=c0, BB=c0), anytime all the three channels (RGB) is all the same the resulting colour is a shade of grey. Each channel can be 0 to 255 (or in HEX: 00 to FF)
*/
}
#cw1MainContainer {
/*
this css selector ("#" followed by "cw1MainContainer") tells the browser that this style block applies to ONLY the element with the id = "cw1MainContainer" - the # tells the browser to match IDs
*/
position: absolute; /* this css property tells the browser that the selected element (in this case id = "cw1MainContainer") will be specifically told where to be displayed using LEFT and TOP (for x and y). 0, 0 being the top left and corner */
left: 20px; /* this css property defines/sets the left position for the selected element; in essence, how far from the left edge it should be placed */
top: 20px; /* this css property defines/sets the top position for the selected element; in essence, how far from the top edge it should be placed */
}
canvas {
/*
this css selector (canvas) tells the browser that this style block applies to ALL <canvas> elements on this page; just because there is only 1 doesnt make any difference
*/
background-color: #fafafa; /* this css property defines/sets the background colour of the selected element (in this case <canvas>) */
border: 1px solid #a0a0a0; /* this css property defines/sets the border of the selected element (in this case <canvas>) */
cursor: crosshair; /* this css property defines/sets the shape and type of the mouse pointer when over this element */
}
#box {
pointer-events: none;
background-color: #000000;
width: 5px;
height: 5px;
}
</style>
<script>
var oCanvas, oCanvasContext; //declare the global variables used to hold and control the canvas element
var sFillColour; //create a global variable used to hold the active/selected colour
var sCanvasColour; //create a global variable used to hold the canvas colour
var iMouseX, iMouseY; //declare the global variables used to hold the mouse's coordinates
var iBrushWidth, iBrushHeight; //declare the global variables used to hold the selected brush sizes
var multiplier = 1 //create a global variable used to hold the multiplier of the brush size
function fnTrackMouse(e) {
//this function is called "everytime" the user's mouse is moved when over the associated element (in this case the canvas)
//we have also added the ability for it to accept a parameter (called e, actually we can call it anything but as event is a reserved work "e" makes some sense
var canvasRect = oCanvas.getBoundingClientRect(); //use this function to dynamically get the size of the canvas and its position
iMouseX=(e.clientX - canvasRect.left - 3); //modify the original position of the mouse by accounting for the position on the canvas; on the x
iMouseY=(e.clientY - canvasRect.top - 3); //modify the original position of the mouse by accounting for the position on the canvas; on the y
var bx = document.getElementById("box");
bx.style.left = (iMouseX)+"px";
bx.style.top = (iMouseY)+"px";
if (e.ctrlKey) { //this checks if the user has pressed the control key to use the eraser funtion
fnSetFillColour(sCanvasColour); //calls the fnSetFillColour function with the background colour of the canvas in the parameter
box.style.backgroundColor = sCanvasColour;
document.body.style.cursor = "none";
}
if (e.buttons==1) { //this checks to see if the user is pressing the left mouse button (1 = the left mouse button)
//the user has pressed the left button - so lets start painting
fnPaint(iMouseX, iMouseY, iBrushWidth, iBrushHeight); //call the fnPaint function and pass it the coordinates and size to paint
}
}
</script>
</head>
</html>
Любая помощь будет оценена по достоинству. Спасибо
Обновлено: вот мой html-код: `
<div id = "cw1MainContainer">
<!-- this div block is only used to hold the HTML canvas element -->
<div id = "cw1CanvasContainer">
<canvas id = "cw1Canvas" onmousemove = "fnTrackMouse(event);" onkeypress = "fnBrushSize(event);"></canvas>
<div id = "box" style = "border: 1px solid #000000; position:absolute;" />
<!--
by specifing the onmouseover event the canvas will call the "fnTrackMouse" function EVERY time the
mouse moves 1 pixel over the canvas.
by passing the JavaScript "event" we are effectively also passing details about the event,
e.g. where the mouse was, what buttons were pressed etc.
-->
</div>
</div>
</body>`
Ваш код работает, но как вы слушаете нажатие кнопки Ctrl? другими словами, когда вы вызываете функцию fnTrackMouse?
@AliSheikhpour посмотри мой ответ



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вместо этого используйте document.documentElementdocument.body
Причина, по которой это не сработало, заключается в том, что стиль переопределяет собственный стиль DOM (css компилируется с помощью специфичность)
В основном *{cursor: none!important;} в css должен решить вашу проблему
Вот JS-код:
function hide(){
document.documentElement.style.cursor = "none";
}<button onclick = "hide()">Try me</button>РЕДАКТИРОВАТЬ!
Чтобы добавить *{cursor: none!important;} в таблицу стилей, вы можете использовать код, как показано ниже:
function hide(){
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = "*{cursor: none!important;}";
document.body.appendChild(css);
}<button onclick = "hide()">Try me</button>Курсор исчезает за пределами моего холста, но не на моем холсте. Я отредактировал свой html в вопросе выше.
по этой причине я рассказал вам о specificity и использовании !important
Но я хочу, чтобы сначала отображался курсор перекрестия, а при нажатии кнопки ctrl курсор становится none
Вероятно, вам следует изменить свойство курсора в элементе canvas, а не в элементе body или *. Это позволяет курсору вернуться в нормальное состояние вне курсора. Кроме того, использование !important не рекомендуется.
Вы правы, но похоже, что ОП хочет скрыть курсор от тела ... ДАВАЙТЕ посмотрим на его / ее реакцию
Я понял, что не использовал свой идентификатор холста div, поэтому мне не нужно использовать !important. Все равно спасибо за помощь!
Возможно, вы пытаетесь получить доступ к DOM перед рендерингом. Пожалуйста, обратитесь к следующему коду.
function canvas(){
var $canvas = document.getElementById("myCanvas");
$canvas.addEventListener('mouseover', function(e){
if (e.ctrlKey){
$canvas.style.cursor = 'none';
} else {
$canvas.style.cursor = 'crosshair';
}
})
}#myCanvas{
cursor: crosshair;
width: 100px;
height: 100px;
background: skyblue;
}<!DOCTYPE html>
<html lang = "en">
<head>
<!-- Meta -->
<meta charset = "UTF-8" />
<title>Javascript Cursor Styles!</title>
<!-- Styles -->
<link rel = "stylesheet" href = "styles/index.processed.css">
<script src = "scripts/index.js"></script>
</head>
<body onload = "canvas()">
<div id='myCanvas'>
</div>
</body>
</html>Я не могу использовать Jquery для этого проекта, но я понял, что должен использовать тег div canvas внутри getElementByID, так что спасибо
Код не содержит jQuery, но все равно работает, так что ура :-)
покажи свой html тоже