国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
How to customize the appearance of Google's custom search engine?
Can I add Google custom search to my website?
How to implement the search box using Google Custom Search?
What is the programmable search element control API?
How to control search results in Google Custom Search?
Can I use Google Custom Search for commercial purposes?
How to change the color of search results in Google Custom Search?
Can I use Google to custom search on my mobile device?
How to add a logo in my Google custom search engine?
Can I use Google to custom search without coding knowledge?
Home Web Front-end JS Tutorial Quick Tip: How to Style Google Custom Search Manually

Quick Tip: How to Style Google Custom Search Manually

Feb 17, 2025 am 09:42 AM

Quick Tip: How to Style Google Custom Search Manually

Core points

  • By manually rendering search forms (without the need to use special GCSE tags), you can manually style Google Custom Search Engine (GCSE), thereby giving you better control over the search input fields and making them look simpler.
  • GCSE callback function ensures that the input is loaded before changing the input properties. This method is more reliable than using the setTimeout method.
  • The Google Search API can be used to create search boxes and result boxes. If an active query exists, a result box is also created. Other customizations can be achieved by looking up the document.
  • Custom style functions can be added to the search div for further customization. This function can be used to change placeholders, delete backgrounds, and add events that remove backgrounds when out of focus.

This article was reviewed by Mark Brown. Thanks to all the peer reviewers at SitePoint for getting SitePoint content to its best!

Website owners often choose to use Google Custom Search Engine (GCSE) to search for their content instead of using built-in and/or custom search features. The reason is simple - much less work and in most cases it can achieve the purpose. If you don't need advanced filters or custom search parameters, GCSE is for you.

In this quick tip, I will show you how to manually render the search form (no need to use special GCSE tags) and result boxes, which allow for finer control and a cleaner search input field Style setting method.

Question

Usually, adding GCSE to your website is as easy as copy-pasting scripts and custom HTML tags to your website. Where you place the special GCSE tag, an input search field will be rendered. Type and start search from this field will perform a Google search based on previously configured parameters (for example, search only sitepoint.com).

A common question is "How to change the placeholder for the GCSE input field?". Unfortunately, the suggested answer is usually wrong, as it uses the unreliable

method to wait for the Ajax call of GCSE to complete (make sure the input is attached to the DOM), and then change the properties via JavaScript. setTimeout

We will also query elements and change attributes using JS, but we will use the callback function provided by GCSE instead of blindly using

, which will ensure that the input is loaded. setTimeout()

Create a GCSE account

Search engine is fully configured online. The first step is to go to the GCSE website and click Add. Follow the wizard to fill in the domain name you want to search for (usually your website URL). Now you can ignore any advanced settings.

After clicking "Finish", you will see three options:

  1. "Get Code", which will guide you through what you have to copy and where to place it so that the search will appear on your website
  2. "Public URL" will show you a work preview of the set search
  3. "Control Panel" is used to customize searches

Go to Control Panel, click Search Engine ID, and note this value for later use.

HTML Settings

To try it out, we will create a basic index.html with the required HTML, as well as an app.js file that contains the functions required for rendering and custom search.

Continue to create a basic HTML file with:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>GCSE test</title>
</head>
<body>

    <h1>GCSE test</h1>
    <div id="searchForm" class="gcse-search-wrapper"></div>
    <div id="searchResults" class="gcse-results-wrapper"></div>
    <??>

</body>
</html>

We added two <div> and used special classes to identify elements where the search form and results should be presented.

Manual rendering function

Now enter your app.js file and add the following:

var config = {
  gcseId: '006267341911716099344:r_iziouh0nw', // 替換為您的搜索引擎ID
  resultsUrl: 'http://localhost:8080', // 替換為您的本地服務(wù)器地址
  searchWrapperClass: 'gcse-search-wrapper',
  resultsWrapperClass: 'gcse-results-wrapper'
};

var renderSearchForms = function () {
  if (document.readyState == 'complete') {
    queryAndRender();
  } else {
    google.setOnLoadCallback(function () {
      queryAndRender();
    }, true);
  }
};

var queryAndRender = function() {
  var gsceSearchForms = document.querySelectorAll('.' + config.searchWrapperClass);
  var gsceResults = document.querySelectorAll('.' + config.resultsWrapperClass);

  if (gsceSearchForms.length > 0) {
    renderSearch(gsceSearchForms[0]);
  }
  if (gsceResults.length > 0) {
    renderResults(gsceResults[0]);
  }
};

var renderSearch = function (div) {
    google.search.cse.element.render(
      {
        div: div.id,
        tag: 'searchbox-only',
        attributes: {
          resultsUrl: config.resultsUrl
        }
      }
    );
    if (div.dataset &&
        div.dataset.stylingFunction &&
        window[div.dataset.stylingFunction] &&
        typeof window[div.dataset.stylingFunction] === 'function') {
      window[div.dataset.stylingFunction](div); // 傳遞div而不是form
    }
};

var renderResults = function(div) {
  google.search.cse.element.render(
    {
      div: div.id,
      tag: 'searchresults-only'
    });
};

window.__gcse = {
  parsetags: 'explicit',
  callback: renderSearchForms
};

(function () {
  var cx = config.gcseId;
  var gcse = document.createElement('script');
  gcse.type = 'text/javascript';
  gcse.async = true;
  gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
    '//cse.google.com/cse.js?cx=' + cx;
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(gcse, s);
})();

First, we declare some variables for configuration. Put the ID you wrote down before into the gcseId field of config. Put the URL of the local index.html file into the resultsUrl field. This is where the search will be redirected to after the user submits the query. Additionally, GCSE will expect to render the result field on the provided URL.

renderSearchForms function checks if the page is loaded, and if it is loaded, the callback function will be responsible for rendering queryAndRender(); or, if the document has not been loaded, set up a callback function to return this later after the document is loaded. place.

queryAndRender function query the DOM with elements of the class provided in config. If the wrapper div is found, renderSearch() and renderResults() are called respectively to render the search and result fields.

renderSearch Functions are where actual magic happens.

We use the Google Search API (more documentation here on how to use the google.search.cse.element object) to create the search box and if there is an active query (result) then the result box is created.

The

render function accepts more parameters than is provided in this example, so be sure to check the documentation if further customization is required. The div parameter actually accepts the ID of the div we are going to render, and the tag parameter indicates what exactly we are going to render ( results or search or both).

In addition, renderSearch() finds the data attribute of the wrapper element, and if the styling-function attribute is given, it will look for the function name in the scope and apply it to the element. This is our chance to style the element.

window.__gcse = {
  parsetags: 'explicit',
  callback: renderSearchForms
};

In this code snippet, we set a callback variable in the global scope so that GCSE can use this variable internally and execute the callback function after loading is complete. This makes this method much better than using the setTimeout() solution to edit the placeholder (or anything else) of the input field.

Test run

So far, we have included everything we need to render the search box and the results. If you have node.js installed, go to the folder where the index.html and app.js files are placed and run the http-server command. By default, this will provide the contents in the folder on port 8080 on localhost.

Quick Tip: How to Style Google Custom Search Manually

Style function

Now we are going to add custom style functions to the search div. Return index.html and add a #searchForm attribute on the styling-function div:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>GCSE test</title>
</head>
<body>

    <h1>GCSE test</h1>
    <div id="searchForm" class="gcse-search-wrapper"></div>
    <div id="searchResults" class="gcse-results-wrapper"></div>
    <??>

</body>
</html>

Now go to app.js, at the top of the file, under the config variable declaration, add a new function:

var config = {
  gcseId: '006267341911716099344:r_iziouh0nw', // 替換為您的搜索引擎ID
  resultsUrl: 'http://localhost:8080', // 替換為您的本地服務(wù)器地址
  searchWrapperClass: 'gcse-search-wrapper',
  resultsWrapperClass: 'gcse-results-wrapper'
};

var renderSearchForms = function () {
  if (document.readyState == 'complete') {
    queryAndRender();
  } else {
    google.setOnLoadCallback(function () {
      queryAndRender();
    }, true);
  }
};

var queryAndRender = function() {
  var gsceSearchForms = document.querySelectorAll('.' + config.searchWrapperClass);
  var gsceResults = document.querySelectorAll('.' + config.resultsWrapperClass);

  if (gsceSearchForms.length > 0) {
    renderSearch(gsceSearchForms[0]);
  }
  if (gsceResults.length > 0) {
    renderResults(gsceResults[0]);
  }
};

var renderSearch = function (div) {
    google.search.cse.element.render(
      {
        div: div.id,
        tag: 'searchbox-only',
        attributes: {
          resultsUrl: config.resultsUrl
        }
      }
    );
    if (div.dataset &&
        div.dataset.stylingFunction &&
        window[div.dataset.stylingFunction] &&
        typeof window[div.dataset.stylingFunction] === 'function') {
      window[div.dataset.stylingFunction](div); // 傳遞div而不是form
    }
};

var renderResults = function(div) {
  google.search.cse.element.render(
    {
      div: div.id,
      tag: 'searchresults-only'
    });
};

window.__gcse = {
  parsetags: 'explicit',
  callback: renderSearchForms
};

(function () {
  var cx = config.gcseId;
  var gcse = document.createElement('script');
  gcse.type = 'text/javascript';
  gcse.async = true;
  gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
    '//cse.google.com/cse.js?cx=' + cx;
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(gcse, s);
})();

Now try loading the test page again and you will see the correct placeholder.

Quick Tip: How to Style Google Custom Search Manually

Conclusion

Google custom search engines are very effective for quick setup of simple searches, especially when the website is just static HTML. With just a small amount of JavaScript code, you can customize search forms and result pages to provide users with a more seamless experience.

Are you using GCSE, or have you found a better solution? Please comment below!

FAQ on setting Google's custom search styles

How to customize the appearance of Google's custom search engine?

Customize the appearance of custom Google search engines involving the use of CSS (cascading stylesheets). CSS is a stylesheet language that describes the appearance and formatting of documents written in HTML. You can change the color, font, size, and other elements of search engines. To do this, you need to access the Programmable Search Element Control API, which allows you to customize search elements. You can then add CSS to the correct section to change the look of the search engine.

Can I add Google custom search to my website?

Yes, you can add Google custom searches to your website. Google provides a custom search JSON API that you can use to send GET requests. This API returns search results in JSON format. You can then use these results to create a custom search engine on your website. This allows your users to search for your website or other websites you specify.

Implementing a search box with Google Custom Search involves creating a search engine ID, which you can do on a programmable search engine website. Once you have the ID, you can use the Custom Search Element Control API to create a search box. You can then customize this search box using CSS.

What is the programmable search element control API?

The Programmable Search Element Control API is a set of functions provided by Google that allows you to customize programmable search engines. This includes creating search boxes, customizing the look of search engines, and controlling search results.

You can use the Programmable Search Element Control API to control search results in Google's custom searches. This API provides functions that allow you to specify the website you searched, the number of results returned, and the order in which results are displayed.

Can I use Google Custom Search for commercial purposes?

Yes, you can use Google custom searches for commercial purposes. However, you need to understand the terms of service. For example, you cannot use search engines to display adult content or promote illegal activities.

You can use CSS to change the color of search results in Google's custom search. You need to access the programmable search element control API and add CSS to the correct section. You can change the colors of text, background, and other search result elements.

Can I use Google to custom search on my mobile device?

Yes, you can customize searches using Google on your mobile device. The programmable search engine is designed to be responsive, which means it will adjust to fit the screen size of the device it is viewing. You can also use CSS to customize the look of the search engine to make it more mobile-friendly.

How to add a logo in my Google custom search engine?

You can add logos in my Google custom search engine using CSS. You need to access the programmable search element control API and add CSS to the correct section. You can then add an image URL to display as your logo.

Can I use Google to custom search without coding knowledge?

While you can use Google to customize searches without coding knowledge, it is recommended that you have a certain understanding of HTML and CSS to fully customize your search engine. However, Google provides detailed documentation and tutorials to get you started.

The above is the detailed content of Quick Tip: How to Style Google Custom Search Manually. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

What's the Difference Between Java and JavaScript? What's the Difference Between Java and JavaScript? Jun 17, 2025 am 09:17 AM

Java and JavaScript are different programming languages. 1.Java is a statically typed and compiled language, suitable for enterprise applications and large systems. 2. JavaScript is a dynamic type and interpreted language, mainly used for web interaction and front-end development.

See all articles