Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在HTML/JS/JQ中通过按键更改div颜色_Javascript_Jquery_Html_Css_Input - Fatal编程技术网

Javascript 在HTML/JS/JQ中通过按键更改div颜色

Javascript 在HTML/JS/JQ中通过按键更改div颜色,javascript,jquery,html,css,input,Javascript,Jquery,Html,Css,Input,基本上,我希望能够做的是改变一个单一的div的颜色取决于按键。例如,如果我按“w”,背景色将变为绿色,“s”将变为红色等 我没有发布任何代码链接,因为基本上我只有一个50px乘50px的div,我真的不知道去哪里。也许这真的很容易,但我所知道的编码都来自于Codeacademy的HTML/CSS课程。提前感谢您能给我看或指给我看的任何东西。这并不难 基本上,你必须听按键事件。此事件将为您提供与按下的键对应的代码 如果需要监听多个键,请在以下情况下使用更多的: $(document).keypr

基本上,我希望能够做的是改变一个单一的div的颜色取决于按键。例如,如果我按“w”,背景色将变为绿色,“s”将变为红色等


我没有发布任何代码链接,因为基本上我只有一个50px乘50px的div,我真的不知道去哪里。也许这真的很容易,但我所知道的编码都来自于Codeacademy的HTML/CSS课程。提前感谢您能给我看或指给我看的任何东西。

这并不难

基本上,你必须听按键事件。此事件将为您提供与按下的键对应的代码

如果需要监听多个键,请在以下情况下使用更多的

$(document).keypress(function(e) {
  if (e.which == 13) {
    // key 13 is pressed
  }
  else if (e.which == 14) {
    // key 14 is pressed
  }
});
如果您想知道钥匙代码是什么,这将在控制台中显示号码:

$(document).keypress(function(e) {
  console.log(e.which);
});
最后,如果您的div有一个
#mydiv
id
,则根据示例使用.css()来更改颜色:

$(document).keypress(function(e) {
  if (e.which == 13) {
    $("#mydiv").css("color", "red");
  }
  else if (e.which == 14) {
    $("#mydiv").css("color", "blue");
  }
});

也许有更优雅的方法可以做到这一点(将颜色分配给一个var,将css放在末尾),但这可能有些过分。

结合一些逻辑,从我模拟的东西中获取关键代码。基本上,您可以监听
KeyUp
事件,检查它是哪个键,并执行适当的逻辑

document.onkeyup = function() {
    var keyCode = window.event ? window.event.keyCode : event.which;
    changeColor(keyCode);
}

function changeColor(keyCode) {
    if (keyCode == 87 ) { // w
        document.getElementById.style.background = "red";
    } else if (keyCode == 83 ) { // s
        document.getElementById.style.background = "green";
    } else if (keyCode == someOtherKeyCode) {
        // Other color change
    }
}
您可以参考钥匙代码

但更可靠的检查方法可能只是检查:

document.onkeyup = function (event) {
    var keyCode = window.event ? window.event.keyCode : event.which;
    alert(keyCode);
}
你可以把它放在控制台里,然后测试钥匙


嗨,请检查以下小提琴

我只写了2个字母(W,K),您可以在识别更多的键码后重复此过程

取消对警报行的注释以了解更多的按键代码,一旦取消注释,每次按键都会首先对按键代码发出警报

$(document).ready(function(){

$(document).keydown(function(e) {
   //alert(e.keyCode);

    if(e.keyCode==75)
    {
     //alphabet K 
           $("#square").css("background","green");
    }

   if(e.keyCode==87)
   {
   //alphabet W 
        $("#square").css("background","red");
    }    

});


})

我建议采用一种更具扩展性的方法:

// creating a map of the relation between the keyboard character pressed
// and the colour it should generate; 'color.b' and 'color["b"]' both give
// 'blue' for example:
var colorMap = {
    'b' : 'blue',
    'r' : 'red',
    'w' : 'white',
    'f' : 'fuchsia'
};

// binding the keypress event on the document:    
$(document).on('keyup', function(e){
    // creating a string from the character-code of the pressed key,
    // e.which returns the jQuery-normalised character code,
    // converting that string to lower case:
    var letter = String.fromCharCode(e.which).toLowerCase();

    // using the css() method to set the background-color to the
    // color returned from the colorMap[letter] call:
    $('#swatch').css('background-color', colorMap[letter]);
});

编辑以添加回退(以防止任何不卫生的错误进入控制台或其他任何地方):

要使用纯JavaScript而不是jQuery库,请执行以下操作:

// arguments are required,
// target is the element whose property we're changing,
// event is the event-object,
// propertyName is the name of the property we're changing:
function changeProperty (target, event, propertyName) {
    // if any of those are not supplied, we quit right here:
    if (!target || !event || !propertyName) {
        return false;
    }
    else {
        // if target is a node (and has a nodeType) *and* is an HTMLElement (
        // with a nodeType === 1) we use that, otherwise we assume it's a string
        // and use getElementById() to retrieve that element:
        target = target.nodeType && target.nodeType === 1 ? target : document.getElementById(target);

        // as above, but there's no normalisation of the event.which,
        // so we're relying on browsers to comply with standards:
        var letter = String.fromCharCode(event.which).toLowerCase(),

            // getting the old property-value, using window.getComputedStyle:
            oldPropertyValue = window.getComputedStyle(target,null)[propertyName];

        // setting the style property to the value returned by the colorMap, or
        // to the current value if no value is returned by the colorMap:
        target.style[propertyName] = colorMap[letter] || oldPropertyValue;
    }
}

document.body.addEventListener('keyup', function(e){
    changeProperty(document.getElementById('swatch'), e, 'backgroundColor');
});

以上内容是为以下HTML编写的:

<div id="swatch"></div>

参考资料:

  • jQuery:
  • JavaScript:

因此,每当用户在您的页面上按下一个键,或者当他们的鼠标位于div或其他位置时?那么,一个有趣的否决票;想一想为什么?这个答案有什么问题我没有回答吗?
var colorMap = {
    'b' : 'blue',
    'r' : 'red',
    'w' : 'white',
    'f' : 'fuchsia'
};

$(document).on('keyup', function(e){
    var letter = String.fromCharCode(e.which).toLowerCase();
    // broadly the same as above, but using the anonymous function,
    // i is the index of the current element among the collection returned
    // by the selector;
    // currentColour is the current value of the property we're updating:
    $('#swatch').css('background-color', function(i,currentColour){
        // returns the colorMap[letter] colour or, if one doesn't exist,
        // returns the existing colour instead:
        return colorMap[letter] || currentColour;
    });
});
// arguments are required,
// target is the element whose property we're changing,
// event is the event-object,
// propertyName is the name of the property we're changing:
function changeProperty (target, event, propertyName) {
    // if any of those are not supplied, we quit right here:
    if (!target || !event || !propertyName) {
        return false;
    }
    else {
        // if target is a node (and has a nodeType) *and* is an HTMLElement (
        // with a nodeType === 1) we use that, otherwise we assume it's a string
        // and use getElementById() to retrieve that element:
        target = target.nodeType && target.nodeType === 1 ? target : document.getElementById(target);

        // as above, but there's no normalisation of the event.which,
        // so we're relying on browsers to comply with standards:
        var letter = String.fromCharCode(event.which).toLowerCase(),

            // getting the old property-value, using window.getComputedStyle:
            oldPropertyValue = window.getComputedStyle(target,null)[propertyName];

        // setting the style property to the value returned by the colorMap, or
        // to the current value if no value is returned by the colorMap:
        target.style[propertyName] = colorMap[letter] || oldPropertyValue;
    }
}

document.body.addEventListener('keyup', function(e){
    changeProperty(document.getElementById('swatch'), e, 'backgroundColor');
});
<div id="swatch"></div>