如何在 JavaScript 中返回屏幕的像素深度?
在本教程中,我们将讨论如何在 JavaScript 中返回屏幕的像素深度。JavaScript 中有一个属性,名为像素深度,借助此属性,我们可以快速返回屏幕颜色的像素深度。此像素深度属性以每像素位数返回屏幕的颜色深度,并且此属性是只读的(可以访问属性的值,但不能为其赋值。或者我们可以声明它不能被分配或覆盖)。
基本上,我们返回的是用于存储屏幕像素的位数。可以显示的最大颜色量称为颜色深度,有时也称为"像素深度"和"位深度"。现代显卡支持真彩色(24 位颜色),这是逼真的图像和视频所必需的。
语法
让我们看看使用 JavaScript 返回屏幕颜色像素深度的语法 -
letdepth; // 声明 int 类型的深度 depth = screen.pixelDepth;
在这里我们定义"let"变量(或者我们也可以在 let 的位置使用"var"),然后我们使用 JavaScript 的 screen.pixelDepth 属性将屏幕的颜色深度提供给 let 变量。
注意 - 在 Internet Explorer 9 之前,不支持像素深度属性。但是,pixelDepth和 colorDepth返回的结果是相同的。使用 colorDepth (screen.colourDepth) 属性作为替代方案,因为它受所有浏览器支持。
算法
我们已经看到了上述返回屏幕颜色像素深度的语法,现在我们将逐步了解完整的方法 -
首先,我们将创建 Html 代码的主体。
在主体中,我们将使用"按钮"标签创建一个按钮。
在按钮中,我们将定义"onclick()"事件,该事件将调用我们将在脚本标签中创建的函数。
在脚本中,我们将创建一个变量来存储从"screen.pixelDepth"方法获得的值。
使用'document.write' 方法中我们打印屏幕的颜色像素深度。
示例 1
我们已经了解了获取屏幕像素深度的步骤,现在让我们将这些步骤实现到代码中以更好地理解它 −
<!DOCTYPE html> <html> <head> <script> function display(){ let cur = screen.pixelDepth; document.write("Pixel Depth of the screen is: " + cur); } </script> </head> <body> <h3>Click the below given button to return pixel depth of the screen in JavaScript</h3> <button onclick="display()"> Click me!! </button> </body> </html> <body> <p>Set the width of the columns</p> <button onclick="display()">Change Width</button> <div id="myID"> This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. </div> </body> </html>
在上面的代码中,我们首先定义了代码主体,因为我们使用 <button> 标签创建了一个按钮,该按钮在单击时将调用"display()"函数,该函数由"onclick"事件定义。
我们在脚本标签中定义了"display"函数,它包含变量"cur",该变量将包含方法"screen.pixelDepth"的返回值,最终它将打印在文档中。
注意− 与获取屏幕深度的像素方法相关,我们还有两个与屏幕相关的方法,它们是"screen.width"和"screen.height"。正如方法的语法所示,这些函数分别用于获取屏幕的宽度和高度。
示例 2
让我们看看使用这些函数的代码,并获取屏幕的所有详细信息−
<!DOCTYPE html> <html> <head> <script> function display(){ let height = screen.height; let width = screen.width; let pixel = screen.pixelDepth; document.write("Dimentions of the screen are: "); document.write("<br> Height is: " + height); document.write("<br> Width is: " + width); document.write("<br> depth is: " + pixel); } </script> </head> <body> <h3>Click the below given button to return pixel depth, screen width, and screen height in JavaScript</h3> <button onclick="display()"> Click me!! </button> </body> </html>
在上面的代码中,我们首先定义了代码主体,因为我们使用 <button> 标记创建了一个按钮,该按钮将在单击时调用"display()"函数,该函数由"onclick"事件定义。
我们在脚本标记中定义了"display"函数,它包含变量"height"、"width"和",它将包含方法"screen.height"、"screen.width"和"screen.pixelDepth"的返回值,最后它将在文档中打印这些值。
结论
在本教程中,我们学习了如何在 JavaScript 中返回屏幕的像素深度。JavaScript 中有一个名为像素深度的属性,借助此属性,我们可以快速返回屏幕颜色的像素深度。此像素深度属性以每像素位数返回屏幕的颜色深度,并且此属性是只读的