Изменить тип курсора в Javascript - PullRequest
0 голосов
/ 12 марта 2019

У меня есть эта программа, где я создаю программу для рисования.Когда я нажимаю клавишу 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>`

Ответы [ 2 ]

1 голос
/ 12 марта 2019

Возможно, вы пытаетесь получить доступ к 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>
1 голос
/ 12 марта 2019

Используйте document.documentElement вместо document.body

Причина, по которой это не сработало, заключается в том, что стиль переопределяется собственным стилем DOM (css компилируется по специфичность )

В основном *{cursor: none!important;} в css должен решить вашу проблему

Вот код JS:

function hide(){
 document.documentElement.style.cursor = "none";
}
<button onclick="hide()">Try me</button>

EDIT!

Чтобы добавить *{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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...