如何使背景图像按比例缩小以适应javascript中的按钮大小? [英] How to make background image shrink proportionally to fit button size in javascript?

查看:97
本文介绍了如何使背景图像按比例缩小以适应javascript中的按钮大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用javascript制作一个棋盘。棋盘的正方形(按钮)最初设计为60px乘60px,但现在它们是40px乘40px。

I am making a chessboard in javascript. The chessboard's squares (buttons) were originally designed to be 60px by 60px, but now they are 40px by 40px.

    button 
    {
      width:40px; 
      height:40px; 
      border: 0
    }

然而,一些设计的部分对于这个早期的棋盘仍然是60px乘60px。在Javascript中是否有任何方法可以使图像按比例缩小以适合方形尺寸?目前,图像符合方形大小,但不缩小,所以当我说,

However, some of the pieces that were designed for this earlier chessboard are still 60px by 60px. Is there any way in Javascript to make the images shrink proportionally to fit the square size? Currently, the images fit the square size, but do not shrink, so when I say,

    square.style.backgroundImage = imgLink; // square is the button, imgLink is "WhiteKing.jpg" for example.

我得到这样的作品 -

I get pieces like this -

如果WhiteKing.jpg按比例缩小,它会很合适。有没有办法在Javascript中执行此操作?任何帮助将非常感激。

If the WhiteKing.jpg had shrunk proportionally, it would have fit nicely. Is there a way to do this in Javascript? Any help would be really appreciated.

推荐答案

大多数现代浏览器都支持CSS 背景图片选项,如 background-size ,所以你可能真的使用这样的东西:

Most modern browsers have support for CSS background-image options like background-size, so you may really use something like this:

button{
  width:40px; 
  height:40px; 
  border: 0;
  background-size: 100%; /* To fill the dimensions of container (button), or */
  background-size: 40px auto; /* to specify dimensions explicitly */
}

当然你可以在JavaScript中使用它也是(但最好将它添加到现有的CSS按钮中):

Of course you can use that in JavaScript too (but it's better to add it to already existing CSS for button):

square.style.backgroundSize = '100%';

这篇关于如何使背景图像按比例缩小以适应javascript中的按钮大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆