You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript根据API返回值修改CSS样式并实现条件渲染元素

Solution: Conditional NSFW Label & Image Blur Based on API Response

Let's adjust your code to implement the conditional logic you need. The key is to check the x_restrict value from each artwork object in the API response, then dynamically build the card HTML with the right elements and styles.

Modified JavaScript Code

First, let's rewrite the fetchData function to include the conditional checks:

const url = 'https://api.adoreanime.com/api/pixiv/?type=member_illust&id=12540747&page=1';

function fetchData(url) {
  fetch(url)
    .then((response) => response.json())
    .then(function(data) {
      const cards = data.illusts.slice(0, 6).map((art) => {
        const imgSrc = art.image_urls.medium.replace('i.pximg.net', 'i.pixiv.cat');
        // Check if x_restrict equals 1
        const isNsfw = art.x_restrict === 1;
        
        // Build image container with conditional blur style
        const cardImage = `
          <div class="card__image" style="${isNsfw ? 'filter: blur(10px)' : ''}">
            <a href="https://www.pixiv.net/en/artworks/${art.id}" target="_blank" rel="noopener noreferrer">
              <img src="${imgSrc}" alt="image">
            </a>
          </div>
        `;
        
        // Add NSFW label only if restricted
        const nsfwTitle = isNsfw ? '<span class="card__title">NSFW</span>' : '';
        
        // Combine all parts into a single card
        return `
          <div class="card">
            ${cardImage}
            ${nsfwTitle}
          </div>
        `;
      });
      
      // Insert all generated cards into the wrapper
      const cardWrapper = document.querySelector('.card__wrapper');
      cardWrapper.innerHTML = cards.join('');
    });
}

fetchData(url);

Key Changes Explained

  • Conditional Blur Styling: We use a ternary operator to inject the filter: blur(10px) inline style into the card__image div only when art.x_restrict is 1. If not, the style is omitted, falling back to your CSS default of filter: blur(0px).
  • Conditional NSFW Label: The card__title span is only included in the HTML string if the artwork is marked as restricted (isNsfw is true).
  • Cleaner Array Handling: Replaced the indexed array + counter approach with map() to directly generate an array of card HTML strings—this is more readable and maintainable.
  • Modern DOM Selection: Swapped getElementsByClassName('card__wrapper')[0] for document.querySelector('.card__wrapper') for simpler, more concise DOM targeting.

CSS & HTML Remain Mostly Unchanged

Your existing CSS and HTML don't need major tweaks. Just keep the default card__image filter style in place (it will be overridden by inline styles when needed):

/* Existing CSS stays the same, ensure this line is present */
.card__image {
  filter: blur(0px);
}
<section>
 <main class="card__wrapper">
 </main>
</section>

This setup ensures each card renders exactly as required: blurred with an NSFW label when x_restrict is 1, and normal otherwise.

内容的提问来源于stack exchange,提问作者TravelWhere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 22:27:40