Javascript 如何使用Node和Electron动态更改css样式属性

Javascript 如何使用Node和Electron动态更改css样式属性,javascript,css,node.js,electron,Javascript,Css,Node.js,Electron,我遇到了以下问题:我想访问Electron内部style.css的css属性。问题是我不能使用document.getElementsByClassName(),因为节点中没有document。所需的行为是在按下q键后更改一个div的颜色。 这是我的代码: index.js const url = require('url'); const path = require('path'); const {app, BrowserWindow, globalShortcut} = require(

我遇到了以下问题:我想访问Electron内部
style.css
的css属性。问题是我不能使用
document.getElementsByClassName()
,因为节点中没有
document
。所需的行为是在按下
q
键后更改一个div的颜色。 这是我的代码:

index.js

const url = require('url');
const path = require('path');

const {app, BrowserWindow, globalShortcut} = require('electron');
let mainWindow;

app.on('ready', function(){
    // Create new window
    mainWindow = new BrowserWindow({backgroundColor: '#000000', fullscreen : true, frame : false});
    // Load html in window
    mainWindow.loadURL(url.format({
      pathname: path.join(__dirname, 'index.html'),
      protocol: 'file:',
      slashes:true
    }))
    globalShortcut.register('Esc', () => {
        app.quit();
    });
    globalShortcut.register('q', () => {
      leftLight();
  });

});


//This doesn't work
function leftLight() {
  var element =   ;
  element.style["background-color"] = "yellow";
}
const url = require('url');
const path = require('path');

const {app, BrowserWindow, globalShortcut, ipcMain, webContents} = require('electron');
let mainWindow;

app.on('ready', function(){
    // Create new window
    mainWindow = new BrowserWindow({
      backgroundColor: '#000000',
      fullscreen : true, 
      frame : false,
      icon : __dirname + "/res/icon.jpg",
      webPreferences: {
        nodeIntegration : true
      }
    });
    // Load html in window
    mainWindow.loadURL(url.format({
      pathname: path.join(__dirname, 'index.html'),
      protocol: 'file:',
      slashes:true
    }))
    globalShortcut.register('Esc', () => {
        app.quit();
    });
    globalShortcut.register('q', () => {
      leftLight();

  });

});

function leftLight() {
  mainWindow && mainWindow.webContents.send('key-pressed-q');
  console.log("Sending q pressed to html...");
}
index.html

<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1">

<head>
    <link rel="stylesheet" href="styles.css">
    <title>Document</title>
</head>
<body>
    <div class = rect_green> <h2 class=blocktext >LEFT FENCER</h2></div>
    <div class = rect_red><h2 class=blocktext> RIGHT FENCER</h2> </div>
    <div class = crono> <h2 class=blocktext>3:00</h2></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1">

<head>
    <link rel="stylesheet" href="styles.css">
    <title>Document</title>
</head>
<body>
    <div class = rect_green> <h2 class=blocktext >LEFT FENCER</h2></div>
    <div class = rect_red><h2 class=blocktext> RIGHT FENCER</h2> </div>
    <div class = crono> <h2 class=blocktext>3:00</h2></div>
</body>

<script type="text/javascript">
        var ipc = require('electron').ipcRenderer;
        ipc.on('key-pressed-q', (e) => {
            //var element =  document.getElementsByClassName("rect_green");
            //element.style["background-color"] = "yellow";
            console.log("q pressed in html file");    
        });
    </script>

</html>
编辑

Gr8Miller建议的修改后(仍无通信):
index.html

<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1">

<head>
    <link rel="stylesheet" href="styles.css">
    <title>Document</title>
</head>
<body>
    <div class = rect_green> <h2 class=blocktext >LEFT FENCER</h2></div>
    <div class = rect_red><h2 class=blocktext> RIGHT FENCER</h2> </div>
    <div class = crono> <h2 class=blocktext>3:00</h2></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1">

<head>
    <link rel="stylesheet" href="styles.css">
    <title>Document</title>
</head>
<body>
    <div class = rect_green> <h2 class=blocktext >LEFT FENCER</h2></div>
    <div class = rect_red><h2 class=blocktext> RIGHT FENCER</h2> </div>
    <div class = crono> <h2 class=blocktext>3:00</h2></div>
</body>

<script type="text/javascript">
        var ipc = require('electron').ipcRenderer;
        ipc.on('key-pressed-q', (e) => {
            //var element =  document.getElementsByClassName("rect_green");
            //element.style["background-color"] = "yellow";
            console.log("q pressed in html file");    
        });
    </script>

</html>
可能的副本

尝试创建另一个包含代码的js文件,并从html文档中将其作为脚本加载

将此添加到index.html:

<script type="text/javascript" charset="utf8" src="./pageScript.js"></script>
可能的副本

尝试创建另一个包含代码的js文件,并从html文档中将其作为脚本加载

将此添加到index.html:

<script type="text/javascript" charset="utf8" src="./pageScript.js"></script>

与视图相关的任务应在渲染过程中处理,而不是在主过程中处理。

Electron
中,条目js(
index.js
)在主进程中运行(它充当它创建的所有浏览器窗口的管理器),而浏览器窗口本身在渲染进程中运行。html元素和浏览器窗口中导入/嵌入的js“live”/“run”(在渲染过程中),因此只能在渲染过程中直接访问
文档

就你而言。样式更改任务应在渲染过程中完成:

  • 在按下键时,从主进程发送消息(例如,
    key-pressed-q
    ),以呈现进程:
  • 在接收消息时更改渲染过程中的样式(
    key-pressed-q
    ):
  • index.js

    const url = require('url');
    const path = require('path');
    
    const {app, BrowserWindow, globalShortcut} = require('electron');
    let mainWindow;
    
    app.on('ready', function(){
        // Create new window
        mainWindow = new BrowserWindow({backgroundColor: '#000000', fullscreen : true, frame : false});
        // Load html in window
        mainWindow.loadURL(url.format({
          pathname: path.join(__dirname, 'index.html'),
          protocol: 'file:',
          slashes:true
        }))
        globalShortcut.register('Esc', () => {
            app.quit();
        });
        globalShortcut.register('q', () => {
          leftLight();
      });
    
    });
    
    
    //This doesn't work
    function leftLight() {
      var element =   ;
      element.style["background-color"] = "yellow";
    }
    
    const url = require('url');
    const path = require('path');
    
    const {app, BrowserWindow, globalShortcut, ipcMain, webContents} = require('electron');
    let mainWindow;
    
    app.on('ready', function(){
        // Create new window
        mainWindow = new BrowserWindow({
          backgroundColor: '#000000',
          fullscreen : true, 
          frame : false,
          icon : __dirname + "/res/icon.jpg",
          webPreferences: {
            nodeIntegration : true
          }
        });
        // Load html in window
        mainWindow.loadURL(url.format({
          pathname: path.join(__dirname, 'index.html'),
          protocol: 'file:',
          slashes:true
        }))
        globalShortcut.register('Esc', () => {
            app.quit();
        });
        globalShortcut.register('q', () => {
          leftLight();
    
      });
    
    });
    
    function leftLight() {
      mainWindow && mainWindow.webContents.send('key-pressed-q');
      console.log("Sending q pressed to html...");
    }
    
    mainWindow=新浏览器窗口({
    背景颜色:'#000000',
    全屏:对,
    帧:假,
    网络首选项:{
    无融合:对
    }});
    ...
    函数leftLight(){
    mainWindow&&mainWindow.webContents.send('key-pressed-q');
    }
    
    index.html

    <!DOCTYPE html>
    <html lang="en">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <head>
        <link rel="stylesheet" href="styles.css">
        <title>Document</title>
    </head>
    <body>
        <div class = rect_green> <h2 class=blocktext >LEFT FENCER</h2></div>
        <div class = rect_red><h2 class=blocktext> RIGHT FENCER</h2> </div>
        <div class = crono> <h2 class=blocktext>3:00</h2></div>
    </body>
    </html>
    
    <!DOCTYPE html>
    <html lang="en">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <head>
        <link rel="stylesheet" href="styles.css">
        <title>Document</title>
    </head>
    <body>
        <div class = rect_green> <h2 class=blocktext >LEFT FENCER</h2></div>
        <div class = rect_red><h2 class=blocktext> RIGHT FENCER</h2> </div>
        <div class = crono> <h2 class=blocktext>3:00</h2></div>
    </body>
    
    <script type="text/javascript">
            var ipc = require('electron').ipcRenderer;
            ipc.on('key-pressed-q', (e) => {
                //var element =  document.getElementsByClassName("rect_green");
                //element.style["background-color"] = "yellow";
                console.log("q pressed in html file");    
            });
        </script>
    
    </html>
    
    。。。
    var ipc=要求('electron')。ipc渲染器;
    ipc.on('按键-q',(e)=>{
    控制台日志(e);
    var元素=;
    element.style.backgroundColor=“黄色”;
    });
    ...
    
    于2019-11-18年添加

    您的代码中还有其他错误需要修复,这些错误与electron无关,只是html基础:

    //var element =  document.getElementsByClassName("rect_green");
    //element.style["background-color"] = "yellow";
    
    getElementsByClassName
    返回元素数组(
    array
    ),但不返回单个
    元素。
    
    element.style
    没有名为
    backgroundColor
    的字段,它应该是
    backgroundColor

    渲染进程中的
    console.log
    不会在主进程的控制台中打印日志,而是输出到其宿主浏览器窗口自己的控制台。如果要检查日志,必须首先打开浏览器窗口的Devtools

      // in your `index.js`
    
      // Open the DevTools.
      mainWindow.webContents.openDevTools(); // `console.log` in `index.html` output to its hosting browser window's own console.
    

    与视图相关的任务应在渲染过程中处理,而不是在主过程中处理。

    Electron
    中,条目js(
    index.js
    )在主进程中运行(它充当它创建的所有浏览器窗口的管理器),而浏览器窗口本身在渲染进程中运行。html元素和浏览器窗口中导入/嵌入的js“live”/“run”(在渲染过程中),因此只能在渲染过程中直接访问
    文档

    就你而言。样式更改任务应在渲染过程中完成:

  • 在按下键时,从主进程发送消息(例如,
    key-pressed-q
    ),以呈现进程:
  • 在接收消息时更改渲染过程中的样式(
    key-pressed-q
    ):
  • index.js

    const url = require('url');
    const path = require('path');
    
    const {app, BrowserWindow, globalShortcut} = require('electron');
    let mainWindow;
    
    app.on('ready', function(){
        // Create new window
        mainWindow = new BrowserWindow({backgroundColor: '#000000', fullscreen : true, frame : false});
        // Load html in window
        mainWindow.loadURL(url.format({
          pathname: path.join(__dirname, 'index.html'),
          protocol: 'file:',
          slashes:true
        }))
        globalShortcut.register('Esc', () => {
            app.quit();
        });
        globalShortcut.register('q', () => {
          leftLight();
      });
    
    });
    
    
    //This doesn't work
    function leftLight() {
      var element =   ;
      element.style["background-color"] = "yellow";
    }
    
    const url = require('url');
    const path = require('path');
    
    const {app, BrowserWindow, globalShortcut, ipcMain, webContents} = require('electron');
    let mainWindow;
    
    app.on('ready', function(){
        // Create new window
        mainWindow = new BrowserWindow({
          backgroundColor: '#000000',
          fullscreen : true, 
          frame : false,
          icon : __dirname + "/res/icon.jpg",
          webPreferences: {
            nodeIntegration : true
          }
        });
        // Load html in window
        mainWindow.loadURL(url.format({
          pathname: path.join(__dirname, 'index.html'),
          protocol: 'file:',
          slashes:true
        }))
        globalShortcut.register('Esc', () => {
            app.quit();
        });
        globalShortcut.register('q', () => {
          leftLight();
    
      });
    
    });
    
    function leftLight() {
      mainWindow && mainWindow.webContents.send('key-pressed-q');
      console.log("Sending q pressed to html...");
    }
    
    mainWindow=新浏览器窗口({
    背景颜色:'#000000',
    全屏:对,
    帧:假,
    网络首选项:{
    无融合:对
    }});
    ...
    函数leftLight(){
    mainWindow&&mainWindow.webContents.send('key-pressed-q');
    }
    
    index.html

    <!DOCTYPE html>
    <html lang="en">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <head>
        <link rel="stylesheet" href="styles.css">
        <title>Document</title>
    </head>
    <body>
        <div class = rect_green> <h2 class=blocktext >LEFT FENCER</h2></div>
        <div class = rect_red><h2 class=blocktext> RIGHT FENCER</h2> </div>
        <div class = crono> <h2 class=blocktext>3:00</h2></div>
    </body>
    </html>
    
    <!DOCTYPE html>
    <html lang="en">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <head>
        <link rel="stylesheet" href="styles.css">
        <title>Document</title>
    </head>
    <body>
        <div class = rect_green> <h2 class=blocktext >LEFT FENCER</h2></div>
        <div class = rect_red><h2 class=blocktext> RIGHT FENCER</h2> </div>
        <div class = crono> <h2 class=blocktext>3:00</h2></div>
    </body>
    
    <script type="text/javascript">
            var ipc = require('electron').ipcRenderer;
            ipc.on('key-pressed-q', (e) => {
                //var element =  document.getElementsByClassName("rect_green");
                //element.style["background-color"] = "yellow";
                console.log("q pressed in html file");    
            });
        </script>
    
    </html>
    
    。。。
    var ipc=要求('electron')。ipc渲染器;
    ipc.on('按键-q',(e)=>{
    控制台日志(e);
    var元素=;
    element.style.backgroundColor=“黄色”;
    });
    ...
    
    于2019-11-18年添加

    您的代码中还有其他错误需要修复,这些错误与electron无关,只是html基础:

    //var element =  document.getElementsByClassName("rect_green");
    //element.style["background-color"] = "yellow";
    
    getElementsByClassName
    返回元素数组(
    array
    ),但不返回单个
    元素。
    
    element.style
    没有名为
    backgroundColor
    的字段,它应该是
    backgroundColor

    渲染进程中的
    console.log
    不会在主进程的控制台中打印日志,而是输出到其宿主浏览器窗口自己的控制台。如果要检查日志,必须首先打开浏览器窗口的Devtools

      // in your `index.js`
    
      // Open the DevTools.
      mainWindow.webContents.openDevTools(); // `console.log` in `index.html` output to its hosting browser window's own console.
    

    使用此选项,渲染和主进程之间没有通信。我添加了一些日志以确保,它似乎在html文件的通道中发送但不接收。@是否有任何错误?也许你需要手动启用节点集成,我修改了我的reponse@Norhther你能告诉我你是如何检查
    index.html
    是否收到消息的吗?根据粘贴的代码,还有一些其他错误。使用此选项,渲染和主进程之间没有通信。我添加了一些日志以确保,它似乎在html文件的通道中发送但不接收。@是否有任何错误?也许你需要手动启用节点集成,我修改了我的reponse@Norhther你能告诉我你是如何检查
    index.html
    是否收到消息的吗?根据粘贴的代码,还有一些其他错误。