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

标签 javascript jquery html css input

基本上我想要做的是根据按键改变单个 div 的颜色。前任。如果我按“w”,背景颜色将变为绿色,“s”将变为红色,等等。

我没有发布任何指向我的代码的链接,因为基本上我只有一个 50px x 50px div,而且我真的不知道该去哪里。也许这真的很简单,但我所知道的编码知识都来自 Codeacademy 的 HTML/CSS 类(class)。预先感谢您向我展示或向我指出的任何内容。

最佳答案

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

// 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]);
});

JS Fiddle demo .

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

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;
    });
});

JS Fiddle demo .

使用纯 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');
});

JS Fiddle demo .

以上内容是针对以下 HTML 编写的:

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

引用文献:

关于javascript - 在 HTML/JS/JQ 中通过按键更改 div 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23347402/

相关文章:

javascript - 在 Promise 回调中,此值变为 null

jquery - 比较并选择jquery中具有最高值的行

javascript - 通过 AngularJS 将 ID 应用于选择构建

jquery - 在 qTip 中获取箭头

javascript - 如何在 jquery 动态添加的 html 中呈现 vuejs 组件

html - 在 < 768px 上给 Bootstrap 横幅更高的高度

html - 为什么不 margin : auto 0px; vertically center a block as margin: 0px auto; horizontally centers it?

javascript - Javascript 中回调数组的不同参数

javascript - 在 Three.js 中,当我尝试实例化 OrbitControls 时,出现未捕获的类型错误 : THREE. OrbitControls 不是构造函数

javascript - Web 客户端上的大十进制