vscode插件開發(fā)Api:web視圖api(第一部分)

webview API允許擴展在Visual Studio Code中創(chuàng)建完全可自定義的視圖。例如,內置的 Markdown 擴展使用 Web 視圖來呈現 Markdown 預覽。
Web 視圖自由且強大、可用于構建超出 VS Code 本機 API 支持的復雜用戶界面。
github示例項目
github示例項目2

使用注意

web視圖消耗資源巨大,若能通過vscode本機Api實現功能,則盡可能不要采用此法

跟隨示例來學習web視圖

示例的git地址

web視圖的基礎知識

創(chuàng)建一個命令來開我們的web視圖

再package.json中的 contributes字段下,注冊一個命令,如下圖:



其中catCoding.start是我們實際關聯的命令。下面兩個字段是命令的名字和描述

創(chuàng)建web視圖本體

在extension.ts中寫入以下內容


import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    vscode.commands.registerCommand('catCoding.start', () => {
      // Create and show a new webview
      const panel = vscode.window.createWebviewPanel(
        'catCoding', // Identifies the type of the webview. Used internally
        'Cat Coding', // Title of the panel displayed to the user
        vscode.ViewColumn.One, // Editor column to show the new webview panel in.
        {} // Webview options. More on these later.
      );
    })
  );
}

這段代碼額意思是注冊一個名為catCoing.start的命令。該命令調用vscode.window.createWebviewPanel方法創(chuàng)建一個web視圖。其第二個參數Cat Coding是標簽頁的名稱,第三個參數表示web視圖展示在哪一欄的工作區(qū)中
至此我們創(chuàng)建了一個新的web視圖,它有標題,不過沒有內容

為新的web視圖注入html內容

依然是在extension.ts文件中,改為一下內容:

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    vscode.commands.registerCommand('catCoding.start', () => {
      // Create and show panel
      const panel = vscode.window.createWebviewPanel(
        'catCoding',
        'Cat Coding',
        vscode.ViewColumn.One,
        {}
      );

      // And set its HTML content
      panel.webview.html = getWebviewContent();
    })
  );
}

function getWebviewContent() {
  return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Coding</title>
</head>
<body>
    <img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif" width="300" />
</body>
</html>`;
}

如上所示,html的內容添加在webViewPanel的webview.html屬性當中。webview.html是一個完整的html文件的內容,主語語法哦!
我們在這里向html中添加了一張gif圖:一個敲鍵盤的貓貓

內容修改:可以做更多

我們可以多寫一些東西,使得整個頁面內容更加靈活

import * as vscode from 'vscode';

const cats = {
  'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
  'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif'
};

export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    vscode.commands.registerCommand('catCoding.start', () => {
      const panel = vscode.window.createWebviewPanel(
        'catCoding',
        'Cat Coding',
        vscode.ViewColumn.One,
        {}
      );

      let iteration = 0;
      const updateWebview = () => {
        const cat = iteration++ % 2 ? 'Compiling Cat' : 'Coding Cat';
        panel.title = cat;
        panel.webview.html = getWebviewContent(cat);
      };

      // Set initial content
      updateWebview();

      // And schedule updates to the content every second
      setInterval(updateWebview, 1000);
    })
  );
}

function getWebviewContent(cat: keyof typeof cats) {
  return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Coding</title>
</head>
<body>
    <img src="${cats[cat]}" width="300" />
</body>
</html>`;
}

上面的代碼新增的內容是:每秒調用切換一次貓貓的圖片
通過panel.title來修改panel的標題
通過panel.webview.html來修改頁面的內容

生命周期panel.onDidDispose

web視圖有自己的生命周期api。
panel.dispose方法用于關閉web視圖
panel.onDidDispose用于在視圖關閉時調用,使用方法如下:

    panel.onDidDispose(
        () => {
          // When the panel is closed, cancel any future updates to the webview content
          clearInterval(interval);
        },
        null,
        context.subscriptions
      );

讀取當前panel是否為可見狀態(tài)

當選中其他標簽頁時,咱們的web視圖的panel.visible將會變?yōu)閒alse

同一時刻相同web視圖只允許存在一個


當前我們可以同時又多個coding Cat的web視圖,這在很多時候顯然是不符合用戶需求的,我們可以將其改成同一時刻相同web視圖只允許存在一個

import * as vscode from 'vscode';

const cats = {
  'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
  'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif'
};

export function activate(context: vscode.ExtensionContext) {
    // Track currently webview panel
    let currentPanel: vscode.WebviewPanel | undefined = undefined;
  
    context.subscriptions.push(
      vscode.commands.registerCommand('catCoding.start', () => {
        const columnToShowIn = vscode.window.activeTextEditor
          ? vscode.window.activeTextEditor.viewColumn
          : undefined;
  
        if (currentPanel) {
          // If we already have a panel, show it in the target column
          currentPanel.reveal(columnToShowIn);
        } else {
          // Otherwise, create a new panel
          currentPanel = vscode.window.createWebviewPanel(
            'catCoding',
            'Cat Coding',
            vscode.ViewColumn.One,
            {}
          );
          currentPanel.webview.html = getWebviewContent('Coding Cat');
  
          // Reset when the current panel is closed
          currentPanel.onDidDispose(
            () => {
              currentPanel = undefined;
            },
            null,
            context.subscriptions
          );
        }
      })
    );
  }

  
function getWebviewContent(cat: keyof typeof cats) {
  return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Coding</title>
</head>
<body>
    <img src="${cats[cat]}" width="300" />
</body>
</html>`;
}

這里用到的一個zpi是panel.reveal(),該方法用于將視圖重新顯示到當前的工作區(qū)
這里的columnToShowIn就是獲取的當前的工作區(qū)在哪一欄

生命周期onDidChangeViewState

前面我們了解了panel.onDidDispose,下面來了解一個新的生命周期函數onDidChangeViewState
每當 Web 視圖的可見性更改或將 Web 視圖移動到新列時,都會觸發(fā)該事件。我們的擴展可以使用此事件根據 Web 視圖顯示在哪一列中來更改貓:onDidChangeViewState

import * as vscode from 'vscode';


const cats = {
    'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
    'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif',
    'Testing Cat': 'https://media.giphy.com/media/3oriO0OEd9QIDdllqo/giphy.gif'
};

export function activate(context: vscode.ExtensionContext) {
    context.subscriptions.push(
        vscode.commands.registerCommand('catCoding.start', () => {
            const panel = vscode.window.createWebviewPanel(
                'catCoding',
                'Cat Coding',
                vscode.ViewColumn.One,
                {}
            );
            panel.webview.html = getWebviewContent('Coding Cat');

            // Update contents based on view state changes
            panel.onDidChangeViewState(
                e => {
                    const panel = e.webviewPanel;
                    switch (panel.viewColumn) {
                        case vscode.ViewColumn.One:
                            updateWebviewForCat(panel, 'Coding Cat');
                            return;

                        case vscode.ViewColumn.Two:
                            updateWebviewForCat(panel, 'Compiling Cat');
                            return;

                        case vscode.ViewColumn.Three:
                            updateWebviewForCat(panel, 'Testing Cat');
                            return;
                    }
                },
                null,
                context.subscriptions
            );
        })
    );
}

function updateWebviewForCat(panel: vscode.WebviewPanel, catName: keyof typeof cats) {
    panel.title = catName;
    panel.webview.html = getWebviewContent(catName);
}


function getWebviewContent(cat: keyof typeof cats) {
    return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Coding</title>
</head>
<body>
    <img src="${cats[cat]}" width="300" />
</body>
</html>`;
}

加載本地內容

如果你注意看了我們的代碼就會發(fā)現,我們的貓貓的gif路徑是用的線上路徑
為什么不在文件夾中直接放幾張圖呢?
因為Web 視圖在無法直接訪問本地資源的隔離上下文中運行。
這樣做是出于安全原因。
同時這意味著,為了從擴展加載圖像、樣式表和其他資源,或從用戶的當前工作區(qū)加載任何內容,必須使用panel.webview.asWebviewUri函數將 localURI 轉換為 VS Code 可用于加載本地資源子集的特殊 URI。

import * as vscode from 'vscode';
import * as path from 'path';

export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    vscode.commands.registerCommand('catCoding.start', () => {
      const panel = vscode.window.createWebviewPanel(
        'catCoding',
        'Cat Coding',
        vscode.ViewColumn.One,
        {}
      );

      // Get path to resource on disk
      const onDiskPath = vscode.Uri.file(
        path.join(context.extensionPath, 'media', 'cat.gif')
      );

      // And get the special URI to use with the webview
      const catGifSrc = panel.webview.asWebviewUri(onDiskPath);

      panel.webview.html = getWebviewContent(catGifSrc);
    })
  );
}


function getWebviewContent(cat: any) {
    return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Coding</title>
</head>
<body>
    <img src="${cat}" width="300" />
</body>
</html>`;
}

上面的代碼中onDiskPath為gif的localURI,注意其寫法:
path.join(context.extensionPath, 'media', 'cat.gif')拼接路徑
vscode.Uri.file獲取localURI
親測這樣寫也是一樣的:

const onDiskPath = vscode.Uri.file(
        "/g:/vscode-extension-samples-main/vscode-extension-samples-main/webview-sample/media/cat.gif"
      );

再用panel.webview.asWebviewUri轉換成vscode可識別的特殊URI,并從該位置加載gif圖

注意:
默認情況下,Web 視圖只能訪問以下位置的資源:

  • 在擴展的安裝目錄中。
  • 在用戶當前處于活動狀態(tài)的工作區(qū)中。
    使用WebviewOptions.localResourceRoots則能夠允許訪問其他本地資源。

還可以始終使用數據 URI 直接在 Web 視圖中嵌入資源。

控制本地資源訪問:WebviewOptions.localResourceRoots

說到WebviewOptions.localResourceRoots我們需要回頭看看我們創(chuàng)建web視圖時的初始化方法:vscode.window.createWebviewPanel()當時我們介紹了前三個參數的含義,那么第四個參數為什么是個空對象呢?

其實第四個參數就是我們這里說的WebviewOptions.localResourceRoots,它控制我們的視圖可以訪問的本地資源,空對象表示使用默認值,也就是上述默認情況下可以訪問的擴展的安裝目錄中和用戶當前處于活動狀態(tài)的工作區(qū)中。
如果按照下述設置,則表示完全隔離本地環(huán)境,不能訪問任何本地資源:

const panel = vscode.window.createWebviewPanel(
        'catCoding',
        'Cat Coding',
        vscode.ViewColumn.One,
        {
            localResourceRoots: []
        }
      );

可以通過設置對象中l(wèi)ocalResourceRoots的值來使視圖對某些本地資源擁有訪問權限。

vscode.commands.registerCommand('catCoding.start', () => {
      const panel = vscode.window.createWebviewPanel(
        'catCoding',
        'Cat Coding',
        vscode.ViewColumn.One,
        {
            enableScripts: true,
            localResourceRoots: [
            vscode.Uri.file(path.join(context.extensionPath, "media")),
            vscode.Uri.file(vscode.env.appRoot)
        ]
    }

下片段代碼段表示只從擴展中的目錄加載資源

        {
          localResourceRoots: [vscode.Uri.file(path.join(context.extensionPath, 'media'))]
        }

今天先到這里

import * as vscode from 'vscode';
import * as path from 'path';

export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    vscode.commands.registerCommand('catCoding.start', () => {
      const panel = vscode.window.createWebviewPanel(
        'catCoding',
        'Cat Coding',
        vscode.ViewColumn.One,
        {
            localResourceRoots: [
            vscode.Uri.file(path.join(context.extensionPath, "html")),
            vscode.Uri.file(vscode.env.appRoot)
        ]
    }
      );

      // Get path to resource on disk
      const onDiskPath = vscode.Uri.file(
        path.join(context.extensionPath, 'media', 'cat.gif')
      );
      console.log(context.extensionPath,path,path.join(context.extensionPath, 'media', 'cat.gif'),onDiskPath)
      // And get the special URI to use with the webview
      const catGifSrc = panel.webview.asWebviewUri(onDiskPath);
      
      panel.webview.html = getWebviewContent("/g:/vscode-extension-samples-main/vscode-extension-samples-main/webview-sample/media/cat.gif");
    })
  );
}


function getWebviewContent(cat: any) {
    return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Coding</title>
</head>
<body>
    <img src="${cat}" width="300" />
</body>
</html>`;
}

web視圖的主題樣式

web視圖作為vscode的一部分,我們是可以讓其根據vscode的皮膚來自動切換樣式顏色的
VS Code 將主題分為三個類別,并向元素添加一個特殊類以指示當前主題:body

  • vscode-light 亮主題。
  • vscode-dark 暗主題。
  • vscode-high-contrast 高對比度主題。
    下面我們用一個現實例子來說明:
    ①我們在extension.ts的html里面,將body標簽內容改成:
   <body>
               <img src="${catGifPath}" width="300" />
               <h1>我不應該變色</h1>
               <h1 id="lines-of-code-counter">0</h1>

               <script nonce="${nonce}" src="${scriptUri}"></script>
           </body>

②在media/vscode.css里面使用我們上面提到的技巧,根據vscode的主題,來設置id為lines-of-code-counter的標簽的顏色。

body.vscode-light #lines-of-code-counter {
    color: rgb(230, 8, 174);
  }
  
  body.vscode-dark #lines-of-code-counter{
    color: rgb(239, 255, 93);
  }
  
  body.vscode-high-contrast #lines-of-code-counter {
    color: red;
  }

③效果如下:
數字會跟隨vscode的主題切換,而漢字則始終保持同一顏色
【圖片待上傳,截圖待補充】

④完整的文件內容如下
src\extension.ts

import * as vscode from 'vscode';

const cats = {
    'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
    'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif',
    'Testing Cat': 'https://media.giphy.com/media/3oriO0OEd9QIDdllqo/giphy.gif'
};

export function activate(context: vscode.ExtensionContext) {
    context.subscriptions.push(
        vscode.commands.registerCommand('catCoding.start', () => {
            CatCodingPanel.createOrShow(context.extensionUri);
        })
    );

    context.subscriptions.push(
        vscode.commands.registerCommand('catCoding.doRefactor', () => {
            if (CatCodingPanel.currentPanel) {
                CatCodingPanel.currentPanel.doRefactor();
            }
        })
    );

    if (vscode.window.registerWebviewPanelSerializer) {
        // Make sure we register a serializer in activation event
        vscode.window.registerWebviewPanelSerializer(CatCodingPanel.viewType, {
            async deserializeWebviewPanel(webviewPanel: vscode.WebviewPanel, state: any) {
                console.log(`Got state: ${state}`);
                // Reset the webview options so we use latest uri for `localResourceRoots`.
                webviewPanel.webview.options = getWebviewOptions(context.extensionUri);
                CatCodingPanel.revive(webviewPanel, context.extensionUri);
            }
        });
    }
}

function getWebviewOptions(extensionUri: vscode.Uri): vscode.WebviewOptions {
    return {
        // Enable javascript in the webview
        enableScripts: true,

        // And restrict the webview to only loading content from our extension's `media` directory.
        localResourceRoots: [vscode.Uri.joinPath(extensionUri, 'media')]
    };
}

/**
 * Manages cat coding webview panels
 */
class CatCodingPanel {
    /**
     * Track the currently panel. Only allow a single panel to exist at a time.
     */
    public static currentPanel: CatCodingPanel | undefined;

    public static readonly viewType = 'catCoding';

    private readonly _panel: vscode.WebviewPanel;
    private readonly _extensionUri: vscode.Uri;
    private _disposables: vscode.Disposable[] = [];

    public static createOrShow(extensionUri: vscode.Uri) {
        const column = vscode.window.activeTextEditor
            ? vscode.window.activeTextEditor.viewColumn
            : undefined;

        // If we already have a panel, show it.
        if (CatCodingPanel.currentPanel) {
            CatCodingPanel.currentPanel._panel.reveal(column);
            return;
        }

        // Otherwise, create a new panel.
        const panel = vscode.window.createWebviewPanel(
            CatCodingPanel.viewType,
            'Cat Coding',
            column || vscode.ViewColumn.One,
            getWebviewOptions(extensionUri),
        );

        CatCodingPanel.currentPanel = new CatCodingPanel(panel, extensionUri);
    }

    public static revive(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) {
        CatCodingPanel.currentPanel = new CatCodingPanel(panel, extensionUri);
    }

    private constructor(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) {
        this._panel = panel;
        this._extensionUri = extensionUri;

        // Set the webview's initial html content
        this._update();

        // Listen for when the panel is disposed
        // This happens when the user closes the panel or when the panel is closed programmatically
        this._panel.onDidDispose(() => this.dispose(), null, this._disposables);

        // Update the content based on view changes
        this._panel.onDidChangeViewState(
            e => {
                if (this._panel.visible) {
                    this._update();
                }
            },
            null,
            this._disposables
        );

        // Handle messages from the webview
        this._panel.webview.onDidReceiveMessage(
            message => {
                switch (message.command) {
                    case 'alert':
                        vscode.window.showErrorMessage(message.text);
                        return;
                }
            },
            null,
            this._disposables
        );
    }

    public doRefactor() {
        // Send a message to the webview webview.
        // You can send any JSON serializable data.
        this._panel.webview.postMessage({ command: 'refactor' });
    }

    public dispose() {
        CatCodingPanel.currentPanel = undefined;

        // Clean up our resources
        this._panel.dispose();

        while (this._disposables.length) {
            const x = this._disposables.pop();
            if (x) {
                x.dispose();
            }
        }
    }

    private _update() {
        const webview = this._panel.webview;

        // Vary the webview's content based on where it is located in the editor.
        switch (this._panel.viewColumn) {
            case vscode.ViewColumn.Two:
                this._updateForCat(webview, 'Compiling Cat');
                return;

            case vscode.ViewColumn.Three:
                this._updateForCat(webview, 'Testing Cat');
                return;

            case vscode.ViewColumn.One:
            default:
                this._updateForCat(webview, 'Coding Cat');
                return;
        }
    }

    private _updateForCat(webview: vscode.Webview, catName: keyof typeof cats) {
        this._panel.title = catName;
        this._panel.webview.html = this._getHtmlForWebview(webview, cats[catName]);
    }

    private _getHtmlForWebview(webview: vscode.Webview, catGifPath: string) {
        // Local path to main script run in the webview
        const scriptPathOnDisk = vscode.Uri.joinPath(this._extensionUri, 'media', 'main.js');

        // And the uri we use to load this script in the webview
        const scriptUri = webview.asWebviewUri(scriptPathOnDisk);

        // Local path to css styles
        const styleResetPath = vscode.Uri.joinPath(this._extensionUri, 'media', 'reset.css');
        const stylesPathMainPath = vscode.Uri.joinPath(this._extensionUri, 'media', 'vscode.css');

        // Uri to load styles into webview
        const stylesResetUri = webview.asWebviewUri(styleResetPath);
        const stylesMainUri = webview.asWebviewUri(stylesPathMainPath);

        // Use a nonce to only allow specific scripts to be run
        const nonce = getNonce();

        return `<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">

                <!--
                    Use a content security policy to only allow loading images from https or from our extension directory,
                    and only allow scripts that have a specific nonce.
                -->
                <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src ${webview.cspSource}; img-src ${webview.cspSource} https:; script-src 'nonce-${nonce}';">

                <meta name="viewport" content="width=device-width, initial-scale=1.0">

                <link href="${stylesResetUri}" rel="stylesheet">
                <link href="${stylesMainUri}" rel="stylesheet">

                <title>Cat Coding</title>
            </head>
            <body>
                <img src="${catGifPath}" width="300" />
                <h1>我不應該變色</h1>
                <h1 id="lines-of-code-counter">0</h1>

                <script nonce="${nonce}" src="${scriptUri}"></script>
            </body>
            </html>`;
    }
}

function getNonce() {
    let text = '';
    const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (let i = 0; i < 32; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
}

media\vscode.css

:root {
    --container-padding: 20px;
    --input-padding-vertical: 6px;
    --input-padding-horizontal: 4px;
    --input-margin-vertical: 4px;
    --input-margin-horizontal: 0;
}

body {
    padding: 0 var(--container-padding);
    color: var(--vscode-foreground);
    font-size: var(--vscode-font-size);
    font-weight: var(--vscode-font-weight);
    font-family: var(--vscode-font-family);
    background-color: var(--vscode-editor-background);
}

ol,
ul {
    padding-left: var(--container-padding);
}

body > *,
form > * {
    margin-block-start: var(--input-margin-vertical);
    margin-block-end: var(--input-margin-vertical);
}

*:focus {
    outline-color: var(--vscode-focusBorder) !important;
}

a {
    color: var(--vscode-textLink-foreground);
}

a:hover,
a:active {
    color: var(--vscode-textLink-activeForeground);
}

code {
    font-size: var(--vscode-editor-font-size);
    font-family: var(--vscode-editor-font-family);
}

button {
    border: none;
    padding: var(--input-padding-vertical) var(--input-padding-horizontal);
    width: 100%;
    text-align: center;
    outline: 1px solid transparent;
    outline-offset: 2px !important;
    color: var(--vscode-button-foreground);
    background: var(--vscode-button-background);
}

button:hover {
    cursor: pointer;
    background: var(--vscode-button-hoverBackground);
}

button:focus {
    outline-color: var(--vscode-focusBorder);
}

button.secondary {
    color: var(--vscode-button-secondaryForeground);
    background: var(--vscode-button-secondaryBackground);
}

button.secondary:hover {
    background: var(--vscode-button-secondaryHoverBackground);
}

input:not([type='checkbox']),
textarea {
    display: block;
    width: 100%;
    border: none;
    font-family: var(--vscode-font-family);
    padding: var(--input-padding-vertical) var(--input-padding-horizontal);
    color: var(--vscode-input-foreground);
    outline-color: var(--vscode-input-border);
    background-color: var(--vscode-input-background);
}

input::placeholder,
textarea::placeholder {
    color: var(--vscode-input-placeholderForeground);
}

/* #lines-of-code-counter {
color: aqua;
} */

body.vscode-light #lines-of-code-counter {
    color: rgb(230, 8, 174);
  }
  
  body.vscode-dark #lines-of-code-counter{
    color: rgb(239, 255, 93);
  }
  
  body.vscode-high-contrast #lines-of-code-counter {
    color: red;
  }

CSS的其他技巧

在編程中如果想要使用和vscode主題一樣的顏色,怎么獲取比較快呢?
  • 使用CSS變量來獲取,例如:
code {
  color: var(--vscode-editor-foreground);
}
  • 自動補全這些變量名,可以考慮使用vscode插件
除了顏色,還有字體也可以獲取到:

--vscode-editor-font-family- 編輯器字體系列(來自設置)。editor.fontFamily
--vscode-editor-font-weight- 編輯器字體粗細(來自設置)。editor.fontWeight
--vscode-editor-font-size- 編輯器字體大?。▉碜栽O置)。editor.fontSize

對特定主題設置樣式

如果我們不滿足于只對vscode的亮、暗、高對比三種主題設置各自的樣式,而是想對其各自的主題分別設置樣式,例如對主題《One Dark Pro》的樣式進行設計,如下:

body[data-vscode-theme-id="One Dark Pro"] {
    background: hotpink;
}

對于需要編寫針對單個主題的 CSS 的特殊情況,webviews 的 body 元素具有一個名為 data 屬性的數據屬性,該屬性存儲當前活動主題的 ID。這使您可以為 Web 視圖編寫特定于主題的 CSS

支持的媒體格式:

音頻:

  • Wav
  • Mp3
  • Ogg
  • Flac
    視頻:
  • H.264
  • VP8
    注意:使用視頻時,需要保證視頻軌道和音頻軌道都是支持的,不然的話vscode就會播放視頻,但是沒有聲音
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容