【问题标题】:how to change backgound image using sass on focus of another element如何在另一个元素的焦点上使用 css 更改背景图像
【发布时间】:2021-04-23 18:25:27
【问题描述】:

有一个类inputBlog 有一个背景图像。我需要更改此背景图像以聚焦输入元素。

但在 SASS 中找不到如何操作。

JSX:

  <div className={styles.inputBlog}>
    some text
  </div>
</div>
<div className={styles.inputSection}>
  <input type="text"

现有的 CSS:

.inputBlog {
  background: url('image.png')
}
   
.inputSection {
  input {
    border-left: 0;
    
    &:focus {
      .inputBlog {
         background: url('differentimage.png');
      }
    }
  }
}

【问题讨论】:

  • 您能否更好地组织您的问题。您说您想更改输入父级的背景,但唯一的背景样式是 inputBlog 不是输入的父级
  • @UdenduAbasili 嗨,现在好些了吗?
  • background: url('diffirent image');

标签: css reactjs sass


【解决方案1】:

根据你的 JSX 目前的方式,当你专注于 input 时,你不能使用 CSS 或 sass 来改变 inputBlog 。您唯一可以使用的是 JavaScript。所以在我添加 onFocus 和 onBlur 的地方做这样的事情,它们基本上分别检查你何时关注和关注输入组件。 Image Path 代表你想在 CSS/sass 中使用的图像。由于您只发布了 JSX 的一部分,因此我只是将其称为一个组件,因此请使用您实际拥有的组件

import React from 'react';
import Image1 from 'image path';
import Image2 from 'image path';

const Component= () => {
    const [focused, setFocused] = React.useState(false)
const onFocus = () => setFocused(true)
const onBlur = () => setFocused(false)
  React.useEffect(() => {
    const inputBlog = document.querySelector('.inputBlog')
    if(focused){
      inputBlog.style.background = `url(${Image1})` 
   }else{
    inputBlog.style.background = `url(${Image2})` 
}


  }, [focused]);

 return (
        <div className='inputBlog' >
              some text
             </div>
         </div>
           <div className='inputSection'>
                 <input
                    type="text"
                    onFocus={onFocus} 
                    onBlur={onBlur}
    );

}

【讨论】:

    猜你喜欢
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多